Displaying model state errors after ajax call on Razor views - ajax

I have razor view with #Html.ValidationMessageFor helpers and jquery unobtrusive validation setup.
I want to call controller/action and to show eventual model state errors returned by action by using same validation logic that is already set in place.
I've made some code that does it but I was wondering if there is already way to do it automatically, i.e. if I capture HTTP Bad Request as AJAX response, I want to take out model state errors from response body and plug them in to unobtrusive validation.
I'm looking for complete recommended solution, not workarounds :)
Thanks!

You can return errors with Json result (How to get all Errors from asp.net mvc modelState?):
var allErrors = ModelState.Values.SelectMany(v => v.Errors);
Then manually show errors. Get form validator:
var validator = $("form").validate();
Then check that your fields are initialized correctly, for example you can look here (optional step):
validator.settings.rules
OR
validator.settings.messages
If everything is fine, then you could show error:
validator.showErrors({"Password": "Too simple!"});
Where Password is field name and Too simple! is error message.

Related

Where i need to put validation code?

I have a form with a number of fields.
Some of them are userId, userFirstName, userLastName.
When user inputs incorrect userId value then near userId field page must show error message and add this error into validationSummary(this is standart behavior for asp.net mvc unobtrusive validation). If userId is correct then page must remove errors and autopopulate userFirstName and userLastName(This is not standart behavior)
How can i implement this?
Here is what come to my mind:
Remote validation attribute
It has a bad customization in my case. That's why i decide to don't use it.
Add special method for jquery validation plugin ( for example
jQuery.validator.addMethod("userIdValidation", function(value, element) {
//some logic
return something;
}, "Please specify the correct userId"); )
and put there logic for validation and for autopopulate other fields.
In this case i mix validation and other stuff.
3 . Add special method for jquery validation plugin ONLY for validation and add special handler for input change event for autopopulate.
In this case i need to send TWO ajax requests to server for one thing. And ofcourse it is not good too. So what is the right way? I am confused.
Have you thought about using a partial view to display the userFirstName and userLastName?
You can fire an AJAX request that sends the userId, and then returns a partial view of the name fields. Within the controller being called, you can validate the incoming userId, and then grab the name details in one query. If thevalidation fails, you can return the partial view with empty fields.

Using jqgrid, what is the best way to return errors from server side validation when using inline editing?

I am using jqgrid and using the inline editing mode and can't figure out how to return errors back to the client from server side validation rules
I use fluent validation on my serverside to validate before persisting to a database. This works great except I don't see how to return errors when editing in inline mode. If I don't persist the values to the databse, the client still shows the value which should be rejected.
What is the recommended way to return an error after someone commits an inline edit so you will get some popup on the client side showing the error and it will stay in edit state ?
NOTE: this image below is in response to Oleg's comment and answer below
The recommend way is to use any HTTP error code in the response on the submitting of wrong data and to return the error description in the body of the response. If you need some more specific action like displaying another dialog with the error information, setting of focus on a field, marking some fields with CSS class 'ui-state-error' or something like that you should use errorfunc callback function.
If restoreAfterError is false the inline editing will be continued.
UPDATED: I mention in comments that the server should produce the error message as the response. In case of ASP.NET MVC the default message is HTML text which you posted as the first picture. If you use HandleJsonExceptionAttribute which I described in my old answer the error message will be serialized as JSON, but it contains additional information which you don't need to display (like the StackTrace). So you should use errorfunc parameter of editRow or saveRow to decode the server response. You can either use decodeErrorMessage from the already referenced answer or use the $.parseJSON function directly:
errorfunc: function(rowid, res) {
var errorText = $.parseJSON(res.responseText).Message;
$.jgrid.info_dialog($.jgrid.errors.errcap,
'<div class="ui-state-error">' + errorText + '</div>',
$.jgrid.edit.bClose,
{buttonalign: 'right'});
}

asp.net mvc 3 jquery adding validation message manually

I've been search for quite a while and haven't been able to find an answer to this.
I am using asp.net MVC 3 with unobtrusive validation. My model is bound with data annotations for simple validation (required fields, regex, etc..). However, I have more complex validation that occurs on the server. I'm doing an ajax post which returns me validation add'l messages that come from my domain model. All I want to do is put those validation messages on the form in the place of the existing ones. I don't want to use partial views since all I've really got are messages coming back and there isn't a need to refresh the whole view. Also, I'm not adding new rules or new inputs to the form so $.validator.unobtrusive.parse won't work. These are just messages I want to put on the form. The $.post call returns a list of message with which field is/was affected and the validation message.
Here's kind of what I'm looking to do
$.post(url, { someData}, function (data) {
for (message in data.Messages) {
$("#form").validate().addMessage(message.Field, message.Text);
}
});
Thanks for your help
Per request, here's a sample of the returning JSON, it's fairly simple.
{"id":0,"messages":["Level":0,"Message":"Style is required","Name":"Style"}],"operationResult":false}
messages is a list of objects that contain the severity level, the property the error belonged to and the error message. I would use the name in the messages object to match where it want on the form.
I had exactly the same requirement, I actually found the following method.
var validator = $("form").validate();
validator.showErrors({field : "Error Message"})

Use CodeIgniter form validation in a view

I have footer view that's included on all my pages which contains a form. I would like to be able to make use of CI's form validation library to validate the form. Is that possible?
Currently the form posts back to the current page using the PHP_SELF environment variable. I don't want to get it to post to a controller because when validation fails it loads the controller name in the address bar, which is not the desired behaviour.
Any suggestions gratefully received.
Thanks,
Gaz
One way, whilst far from ideal, would be to create a "contact" function in every controller. This could be in the form of a library/helper.
CI doesn't natively let you call one controller from another, although I believe there are extensions that enable this.
Another option would be an AJAX call instead, which would allow you to post to a generic controller, validate etc whilst remaining on the current page.
In this use case, I would definitely go for an AJAX call to a generic controller. This allows you to show errors even before submitting in the origin page.
Another way (slightly more complex), involves posting your form data to a generic controller method, passing it a hidden input containing the current URL.
The generic controller method handling your form can then redirect to the page on which the user submitted the form, passing it the validation errors or a success message using flash session variables: $this->session->set_flashdata('errors',validation_errors()) might do the trick (untested)
The good thing about this is that you can use the generic form-handling method for both the ajax case (suppressing the redirect) and the non-ajax case
AJAX would be best, just like everyone else says.
I would redirect the form to one function in one controller, you could make a controller just for the form itself. Then have a hidden value with the return URL. As far as errors go you could send them back with flashdata.
Just remember to never copy paste code, it a bad practice and guarantees bugs.
//make sure you load the proper model
if ($this->form_validation->run() == FALSE){
// invalid
$redirect = $this->input->post('url');
$this->session->set_flashdata('errors',validation_errors());
redirect($redirect);
} else {
/*
success, do what you want here
*/
redirect('send them where ever');
}

Validate data from CakePHP form with jQuery (AJAX)

I would like to validate both single field and multiple field data from a CakePHP form.
The single field validation should be done on blur from each field while the multiple field validation should be done on submitting the form.
I would like to use the $validate property declared in the Model for validating data and I would like to display the errors near each field (single field validation) and on top of the form (for multiple field validation).
My main goal is to achieve this the most "caky" way (if there is one for validating data with jQuery). I couldn't find any useful advice out there and I'm asking you for some help to get this going.
One of my concerns is how shall I pass data from the form to jQuery and then to the action that does the validation and also how shall I return and display the errors, if there are any.
Thank you in advance!
I'd suggest first making sure everything works without jQuery, then use the jQuery Form plugin to submit your forms via AJAX. If you include the RequestHandler component in your AppController, you should find that your controllers distinguish automatically between AJAX and synchronous requests.
OK, so I coded my own solution to this, but I am still waiting for a more "caky" approach.
I made two generic jQuery functions, one for single field validation and one for multiple field validation. The function should grab the data from the specified form and send it to the form's action via AJAX, to a specially created controller method which will attempt to validate data and output an AJAX response ("" for validation has passed and errors for errors in validation). Then, the result is checked in the jQuery function and the default form behaviour is triggered only if the validation has passed. Otherwise, display the errors and return false; to prevent default submission.

Resources