Show error message with alert box - asp.net-mvc-3

I would like to show error message with alert box in asp.net MVC3 Razor. I used dataanootation for my model. Please see below.
<Required(ErrorMessage:="Name is required")> _
Public Name as string
In client side.
#Html.TextBoxFor(Function(model) model.Content)
#Html.ValidationMessageFor(Function(model) model.Content, "Please type name")
#Html.ValidationSummary()
But the error message show as a label beside of textbox. I want to show only alert box for error message. Thanks all.

<script type="text/javascript">
#if (!ViewContext.ViewData.ModelState.IsValid)
{
var sb = new StringBuilder();
foreach (var modelState in ViewContext.ViewData.ModelState.Values)
{
foreach (var error in modelState.Errors)
{
sb.Append(error.ErrorMessage);
}
}
#:alert('#sb.ToString()');
}
</script>

Related

Required Field Validation in ASP MVC using Kendo UI

I have a textbox and want to display the field is required when the form gets submitted. The error message do appear in case i click on the textbox and tab to go to next textbox. I have the 'Required' data annotation on my model like this:
[DisplayName("Shipment Number")]
[Required]
public string ShipmentNumber { get; set; }
My View looks like this:
<div class="col-sm-8">
#Html.TextBoxFor(model => model.ShipmentNumber, new {#class = "form-control", #maxlength = "8", #title = "Maximum length is 8"})
#Html.ValidationMessageFor(model => model.ShipmentNumber)
</div>
Oh, i also added these in $function:
$("form").kendoValidator();
$.validator.setDefaults({
ignore: ""
});
When i leave the textbox blank and submit the form, the form gets submitted without showing the error message i.e. 'The Shipment Number is required!'.
P.S: I also tried DataAnnotation:
[Required(ErrorMessage = "ShipmentNumber Is Required")]
Does anyone know how i can achieve this?
Update:
This fixed it:
Changes in Razor code to make textbox required and added required error message.
#Html.TextBoxFor(model => model.ShipmentNumber, new {#class = "form-control", #maxlength = "8", #title = "Maximum length is 8", data_required_msg = "Shipment Number is required!", required = "required" })
In button submit code in javascript, did this:
var validator = $(".form-horizontal").kendoValidator().data("kendoValidator");
if (validator.validate()) {
//code that needs to be executed if it is valid
}
Note: I also got rid of data annotation from modal class, #Html.ValidationMessageFor and $("form").kendoValidator code.
Try forcing the validation when you click your button:
// Validate the input when the Save button is clicked
$("#save").on("click", function() {
if (validator.validate()) {
// If the form is valid, the Validator will return true
save();
}
});
or
$("form").submit(function(event) {
event.preventDefault();
if (validator.validate()) {
status.text("Hooray! Your tickets has been booked!")
.removeClass("invalid")
.addClass("valid");
} else {
status.text("Oops! There is invalid data in the form.")
.removeClass("valid")
.addClass("invalid");
}
});
See http://docs.telerik.com/kendo-ui/framework/validator/overview

MVC3 C# TextArea/CkEditor validation issue

I have an MVC3 C# .Net Web App. We are using the ckEditor library to enhance the TextAreas in our app. When using a standard TextArea, the Validation operates correctly. However, in the enhanced TextAreas (implementing the ckEditor), when submitting the page, the Validation fires an error. "Description is Required" even when though there is data present in the TextArea. Upon a second click of the Submit, the form submits fine.
Domain class property:
[Display(Name = "Description")]
[Required(ErrorMessage = "Description is required.")]
public virtual string Description { get; set; }
HTML:
<td style="border: 0;text-align:left " >
#Html.TextAreaFor(model => model.Description,
new
{
rows = 5,
cols = 100,
#class = "celltext2 save-alert"
})
#Html.ValidationMessageFor(model => model.Description)
</td>
I think that applying the ckEditor attributes is messing it up somehow. Ideas?`
Let me clarify more. We have a .js file that queries the controls and then does ckEditor initialzation. when I remove the $(this).ckeditor({}) it works fine.
JS File:
$('textarea').each(function () {
$(this).ckeditor({});
});
Something like this might work:
$('textarea').each(function () {
var textarea = $(this);
$(this).ckeditor({}).on('blur', function() {
textarea.html( $(this).html() );
});
});
EDIT(I've never used the jQuery adapter, after a small lesson I found this to work, the above the blur never fires and $(this).html() is not defined):
$('textarea').each(function () {
var textarea = $(this);
textarea.ckeditor(function () {
textarea.ckeditorGet().on('blur', function () {
textarea.html( this.getData() );
});
});
});
I think it's a little simpler than that. CKE creates an iframe that it is used instead of the actual textarea and you do correctly need to update the contents of the textarea with the data inside CKEditor before submitting. I would suggest, however, that you do this on submit instead of on blur. I would recommend setting an id to the relevant DOM elements but you get the idea.
// Replace textarea(s)
$('textarea').each(function () {
$(this).ckeditor({});
});
// Bind on submit event to update the text
$('form').submit(function() {
// Upate textarea value with the ckeditor data
$('textarea').val(CKEDITOR.instances.ValueCKE.getData());
});

Calling multiple action methods (using ajax) and showing the result of last in a new tab

I have a form in which I need to call two action methods, one after the other. This is how the flow goes.
First I check if the prerequisite data is entered by the user. If not then I show a message that user needs to enter the data first.
If all the prerequisite data is entered, I call an action method which return data. If there is no data returned then I show a message "No data found" on the same page.
If data is returned then I call another action method present in a different controller, which returns a view with all the data, in a new tab.
The View:
#using (Ajax.BeginForm("Index", "OrderListItems", null, new AjaxOptions { OnBegin = "verifyRequiredData"}, new { #id = "formCreateOrderListReport", #target = "_blank" }))
{
//Contains controls and a button
}
The Script in this View:
function verifyRequiredData() {
if ($("#dtScheduledDate").val() == "") {
$('#dvValidationSummary').html("");
var errorMessage = "";
errorMessage = "<span>Please correct the following errors:</span><ul>";
errorMessage += "<li>Please enter Scheduled date</li>";
$('#dvValidationSummary').append(errorMessage);
$('#dvValidationSummary').removeClass('validation-summary-valid').addClass('validation-summary-errors');
return false;
}
else {
$('#dvValidationSummary').addClass('validation-summary-valid').removeClass('validation-summary-errors');
$('#dvValidationSummary').html("");
$.ajax({
type: "GET",
url: '#Url.Action("GetOrderListReport", "OrderList")',
data: {
ScheduledDate: $("#dtScheduledDate").val(),
Crews: $('#selAddCrewMembers').val(),
Priorities: $('#selPriority').val(),
ServiceTypes: $('#selServiceTypes').val(),
IsMeterInfoRequired: $('#chkPrintMeterInfo').val()
},
cache: false,
success: function (data) {
debugger;
if (data !== "No data found") {
//var newUrl = '#Url.Action("Index", "OrderListItems")';
//window.open(newUrl, '_blank');
return true;
} else {
//Show message "No data found"
return false;
}
}
});
return false;
}
}
The "GetOrderListReport" Action method in "OrderList" Controller:
public ActionResult GetOrderListReport(OrderListModel model)
{
var contract = new OrderReportDrilldownParamDataContract
{
ScheduledDate = model.ScheduledDate
//Setting other properties as well
};
var result = OrderDataModel.GetOrderList(contract);
if (string.IsNullOrWhiteSpace(result) || string.IsNullOrEmpty(result))
{
return Json("No data found", JsonRequestBehavior.AllowGet);
}
var deserializedData = SO.Core.ExtensionMethods.DeserializeObjectFromJson<OrderReportDrilldownDataContract>(result);
// send it to index method for list
TempData["DataContract"] = deserializedData;
return Json(deserializedData, JsonRequestBehavior.AllowGet);
}
The last action method present in OrderListItems Controller, the result of which needs to be shown in a new tab:
public ActionResult Index()
{
var deserializedData = TempData["DataContract"] as OrderReportDrilldownDataContract;
var model = new OrderListItemViewModel(deserializedData);
return View(model);
}
The problem is that I am not seeing this data in a new tab, although I have used #target = "_blank" in the Ajax.BeginForm. I have also tried to use window.open(newUrl, '_blank') as can be seen above. But still the result is not shown in a new tab.
Please assist as to where I am going wrong?
If you are using the Ajax.BeginForm you shouldn't also be doing an ajax post, as the unobtrusive ajax library will automatically perform an ajax post when submitting the form.
Also, if you use a view model with data annotation validations and client unobtrusive validations, then there would be no need for you to manually validate the data in the begin ajax callback as the form won't be submitted if any validation errors are found.
The only javascript code you need to add in this scenario is a piece of code for the ajax success callback. That will look as the one you currently have, but you need to take into account that opening in new tabs depends on the browser and user settings. It may even be considered as a pop-up by the browser and blocked, requiring the user intervention to allow them as in IE8. You can give it a try on this fiddle.
So this would be your model:
public class OrderListModel
{
[Required]
public DateTime ScheduledDate { get; set; }
//the other properties of the OrderListModel
}
The form will be posted using unobtrusive Ajax to the GetOrderListReport of the OrderList controller. On the sucess callback you will check for the response and when it is different from "No data found", you will then manually open the OrderListItems page on a new tab.
This would be your view:
#model someNamespace.OrderListModel
<script type="text/javascript">
function ViewOrderListItems(data){
debugger;
if (data !== "No data found") {
var newUrl = '#Url.Action("Index", "OrderListItems")';
//this will work or not depending on browser and user settings.
//passing _newtab may work in Firefox too.
window.open(newUrl, '_blank');
} else {
//Show message "No data found" somewhere in the current page
}
}
</script>
#using (Ajax.BeginForm("GetOrderListReport", "OrderList", null,
new AjaxOptions { OnSucces= "ViewOrderListItems"},
new { #id = "formCreateOrderListReport" }))
{
#Html.ValidationSummary(false)
//input and submit buttons
//for inputs, make sure to use the helpers like #Html.TextBoxFor(), #Html.CheckBoxFor(), etc
//so the unobtrusive validation attributes are added to your input elements.
//You may consider using #Html.ValidationMessageFor() so error messages are displayed next to the inputs instead in the validation summary
//Example:
<div>
#Html.LabelFor(m => m.ScheduledDate)
</div>
<div>
#Html.TextBoxFor(m => m.ScheduledDate, new {id = "dtScheduledDate"})
#Html.ValidationMessageFor(m => m.ScheduledDate)
</div>
<input type="submit" value="Get Report" />
}
With this in place, you should be able to post the data in the initial page using ajax. Then based on the response received you will open another window\tab (as mentioned, depending on browser and user settings this may be opened in a new window or even be blocked) with the second page content (OrderListItems).
Here's a skeleton of what I think you are trying to do. Note that window.open is a popup though and most user will have popups blocked.
<form id="formCreateOrderListReport">
<input type="text" vaule="testing" name="id" id="id"/>
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$('#formCreateOrderListReport').on('submit', function (event) {
$.ajax({
type: "POST",
url: '/home/test',
data: { id: $('#id').val()},
cache: false
}).done(function () {
debugger;
alert("success");
var newUrl = '/home/contact';
window.open(newUrl, '_blank');
}).fail(function () {
debugger;
alert("error");
});
return false;
});
</script>
Scale down the app to get the UI flow that you want then work with data.

how to use custom validation message for html form in liferay6 with custom portlet?

I am using liferay to develop a custom portlet (mvc portlet) my problem is that i have one form in jsp page in HTML and and what i want is to validate some field of the forms.and on submit button its redirecting to another page.the validation i have done is working but what happen is when am clicking the submit button its redirect to another page and on that page its just showing default error from liferay. What i want is to display same page if request not completed with the error message near the field which validation has false.
How can i solve this issue?
this is my code to checking validation while add method in action class
public void addRestaurant(ActionRequest request, ActionResponse response) {
log.info("Inside addRegistration");
List<String> errors = new ArrayList<String>();
restaurant rest = RestaurantActionUtil
.getRestaurantFromRequest(request);
boolean restValid = RestaurantValidator
.validateRestaurant(rest, errors);
if (restValid) {
try {
log.info(rest);
restaurant test = restaurantLocalServiceUtil
.addrestaurant(rest);
if (test == null) {
log.error("Restaurant was Found Null");
response.setRenderParameter("jspPage", errorJSP);
return;
}
} catch (SystemException e) {
log.error(e);
/*
* If there is an error then divert the control to the error
* page.
*/
response.setRenderParameter("jspPage", errorJSP);
return;
}
SessionMessages.add(request, "restaurant-added");
return;
} else {
for (String error : errors) {
SessionErrors.add(request, error);
}
SessionErrors.add(request, "error-while-adding");
request.setAttribute("rest", rest);
return;
}
}
This is my validator class
public class RestaurantValidator {
public static boolean validateRestaurant(restaurant rest, List errors) {
boolean valid=true ;
if (Validator.isNull(rest.getName())) {
errors.add("Name-required");
valid = false;
}
if (Validator.isNull(rest.getLicensekey())) {
errors.add("license-key-required");
valid = false;
}
following is my view.jsp code
Restaurant Name*
" />
<span class="help-block">help block</span>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<label>License Key<span class="f_req">*</span></label>
<liferay-ui:error key="license-key-required" message="license-key-required" />
<input type="text" name="licensekey" class="span8" value="<%=restaurantOBJ.getLicensekey() %>"/>
</div>
</div>
the error message is deisplaying on the redirected page with following way rather then on same page i want the error near textbox of name with the error of "Name_required"
The error message is displaying on the redirected page the following way rather then on same page, I want the error near the name-textbox with the error of "Name_required".
what I want is when name is blank then it should not submit the form and give error near text box of name in my view.jsp page.
I would try to answer your question, try to set a actionResponse.setRenderParameter("valid", "NO"); in your addRestaurant method if the validation fails.
And get this parameter in the doView method and set the renderPage accordingly in this method: include(renderPage, renderRequest, renderResponse); at the end of the doView method.
If you can provide all the information in your question with nice formatting like the validator method, <aui:form> and the javascript method called on onSubmit then we can go ahead with looking for other solution.
In the mean-while you can try this out and see if it works. :-)

Issue with validation on Razor View in MVC

I am building wizard step demo application with MVC3 and using razor view engine as begineer level.
I came across on problem with validation when hide & show control through javascript.
Please look my code section as per below
<div class="editor-field">
#Html.EditorFor(model => model.CheckName2)
#Html.ValidationMessageFor(model => model.CheckName2)
</div>
my javascript function as per below, hide & show on some condition
// attach nextStep button handler
$("#next-step").click(function () {
var $step = $(".wizard-step:visible"); // get current step
//check if URL2 is having any content
var val = $("#URL2").val();
if (val == "") {
$("#CheckName2").hide();
//want to remove validation here
}
else {
$("#CheckName2").show();
//want to add validation here
}
var validator = $("form").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
How can i handle validation here?
thanks in advance.
Force validation of your form with $("#IdOfFormYouEdit").validate(); or $("#IdOfTextbox").validate(); to validate only one element.
This is possible if you have put validation attributes on your view model classes. If you don't you can add validation on an element by adding the data-val attributes. For example:
<input type="text" data-val="true" data-val-number="The field someField must be a number." data-val-required="SourceId required" />

Resources