MVC3 Razor Ajax partial page validation - asp.net-mvc-3

I have a wizard style page that I want to validate a page at a time. So before the user can move off the (partial) page I submit the inputs from the div for validation. Client side validation works OK but on some pages there are one or more fields I need to validate on the server. Yes I know about remote validation.
I can get the server side validation done without a problem. The issue I have is how do I display the errors on the correct fields? I can locate the fields in the div and find the span where the error message is suppose to go. But I just can't get the message to display.
I must be missing something when updating the field span. I would have thouht that there is a jQuery routine to add error information to a field. I need something similar to the controllers AddModuleError. So when I get return from my $.Post I can set error text on the appropriate fields.
Any suggestions?

A potential solution to your problem might be in this article "Client side validation after Ajax Partial View result in ASP.NET MVC 3"
Basically, once you get your html from the post you can invoke validation using jQuery.validator.unobtrusive.parse()
As per the example in the article;
$.post("YourAction", { data: <your form data> },
function(htmlContent){
$('#container').html(htmlContent);
jQuery.validator.unobtrusive.parse('#content')
}
Worth looking into

If you are using the included RemoteAttribute, or the version I linked to in my answer to your other remote validation question, then you should not have to worry about displaying the error, as both work with the ValidationMessage helpers to automatically display errors.
Have you added Html.ValidationMessage(...) or Html.ValidationMessageFor(...) for each field to be validated?

Related

Manually bind JQuery validation after Ajax request

I'm requesting an ASP.net MVC view into a live box and the view contains form fields that have been marked up with attributes to be used by JQuery's unobtrusive validators plug-in.
The client script is not however working and my theory is that its because the validation framework is only being triggered on page load which has long since passed by the time the MVC view has been loaded into the live box.
Thus how can I let the validation framework know that it has new form fields to fix up?
Cheers, Ian.
var $form = $("form");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
You may take a look at the following blog post. And here's another one.
Another option, rather trick, which worked for me. Just add following line in the beginning of the partial view which is being returned by ajax call
this.ViewContext.FormContext = new FormContext();
Reference
For some reason I had to combine bjan and dfortun's answers...
So I put this in my view:
#{
this.ViewContext.FormContext = new FormContext();
}
And this execute this after the ajax call finishes:
var form = $("#EnrollmentForm");
form.unbind();
form.data("validator", null);
$.validator.unobtrusive.parse(document);
form.validate(form.data("unobtrusiveValidation").options);
I had a similar issue. I had a form that was using Ajax requests to re-display a part of the form with different form fields. I used unobtrusive validation by manually doing it on the client side using the
#Html.TextBoxFor
for my text boxes. For some reason the validation works when attempting to submit with invalid fields (i.e., the text boxes get outlined in red and the appropriate error messages display with the content I put in the
data_val_required
attribute, for example.
However, after I click a button that makes an Ajax request to modify the form with different fields and then submit again, only the red outline on the invalid fields display, but no error messages are rendered.
bjan's trick worked for me, but I still can't see what was causing the issue. All the HTML necessary to carry out the client-side validation was there I just can't figure out why the error message attribute values wouldn't display.
All I can think of is that the jQuery validation code doesn't make a second attempt to check the form fields after a submit was made.

How can I add a URL parameter but hide others in a POST - Spring MVC

I'm trying to add a URL parameter within a Spring MVC application. It's a basic search page that shows results.
In the search page, there is a form that is set to POST. There are many hidden fields and other fields I don't want in the URL. So, I don't want to do a GET.
I do want the search query in the URL. So after clicking the search button, the resulting search results page needs to have a URL like /search?query=hello
To get it to work, I'm creating a RequestMapping method in the Spring MVC Controller and doing a redirect: tacking on the query parameter. However, I'm not sure using a redirect is the best answer, seems there could be performance concerns redirecting as well.
I looked around and noticed folks using javascript and the location object, but setting the location object obviously relaunches the URL you set it to. I also looked at the HTTPServletResponse & HTTPServletRequest objects, but couldn't find much.
Any thoughts on how I can force the search parameter to be added to the URL?
Your form will have an 'action' specified telling it where to POST to. I'd have thought you could attach an onclick event to your submit button (or an onsubmit event to your form) that updates the action url by appending "?query=" to it.
document.<form name>.action += "?query=...";
Then you just have to worry about someone posting your form without JavaScript enabled - in this case you could fall back to your redirect.
I don't know how the server technology so I can't say if it will be happy giving you both GET and POST parameters, if not you'll have to manually strip the GETs out of the URL.
But anyway, this seems like a rather odd situation to be in - is it really that big a deal to show the parameters in the URL? Anything that gets posted by an HTML form can still be inspected with the right tools, it's just ever so slightly more difficult.
I wanted to provide a more complete answer to my question with code. The previous user helped me down this path, so I'll keep it as the accepted answer. However, there is one item to note:
If you add on to the action, and you have an input text box with the same name, the page posts a duplicate value like: query=hello,hello.
So, I needed to remove the name on the input box, and use the following javascript. Note, I am using the prototype.js framework:
Event.observe(window, 'load', function(event) {
Event.observe('searchForm', 'submit', function(event) {
$('searchForm').action += "?query="+$('searchBox').value;
});

ASP.NET MVC 3 Dynamic Controls and Unobtrusive Validation

Good afternoon everyone. I was wondering if there is anyway to have the MVC framework automatically wire up the data-val* attributes on the controls or do we need to manually create and apply the attributes to dynamic content?
I have a view that initially calls a partial view passing in the main viewmodel. This partial view is bound to a complex property on my main viewmodel. The partial view simply contains a set of cascading dropdown lists. On initial load of the page I have a call to #Html.Partial("PartialName", Model), the two dropdown lists’ validation works perfectly if I try to submit without selecting proper values. I also have another button on the page that if clicked loads another instance of the partial view on the page. If I now try to submit the form these controls, although they are bound to the same model and although I have set the correct .ValidationMessageFor helpers, no validation appears for them since the dropdownlists do not appear to be generated with the data-val* attributes. Is there any way that I can get them to appear correctly? I also noticed that the associated <span /> tag associated to the .ValidationMessageFor is not generated either. Has anyone run into this problem as well, if so how did you resolved?
UPDATE
Here is the javascript function that I call to load the partial on the button's onClick event:
function AddNewVehicle() {
$.ajax({
type: 'GET',
url: '/ReservationWizard/AddVehicleToReservation',
data: $('#reservation-wizard-form').serialize(),
dataType: 'HTML',
async: true,
success: function (data) {
if (data != null) {
$('#vehicle-selection-container').append(data);
}
}
});
}
The problem is that if you are not inside a form context, the HTML helpers such as TextBoxFor do not output any client validation data-* attributes. The first time when the page loads you invoke your Html.RenderPartial inside an Html.BeginForm() but later when you use AJAX to append form elements there is no longer this form context and there won't be any data-* client validation attributes generated. One possible solution would be to put the form inside the partial and then update the entire form during the AJAX call and in the success callback re-parse the client validation rules using $.validator.unobtrusive.parse('#vehicle-selection-container').
But if you want to keep only a single element inside the partial you are pretty much on your own :-) Here's a blog post which covers your scenario that you might take a look at.
So what can I say: unobtrusive client validation is great on paper and Scott Gu's blog posts but at some stage of the development of real world applications people start to realize its limitations. That's one of the reasons why I directly use the jquery.validate plugin and no MS jquery.unobtrusive. And, yes I know that I repeat my server validation logic in the javascript and yes I don't care because I have total control. Oh, and on the server I use FluentValidation.NET instead of data annotations for pretty much the same reasons as the client side part :-)
So maybe some day in MVC 4 Microsoft will finally make validation right (imperative vs declarative) but until this day comes, we just need to be searching for workarounds.

Validator plugin firing with links and on submit

I have a web form which is split up into several HTML pages.
I am using the validation plug-in to check fields on submit and this is working great.
The spec says that users should be able to navigate through the form, both linearly (just using the submit buttons to go from page to page) and also to skip to any particular page.
I have a unordered list with the links at the top of each page. I'm looking to fire the validation both on submit and when one of these links is clicked but don't know if this is possible.
For info, I'm currently firing the validation this way:
$("form#courseDetails").validate({
rules: {
studiedBefore: "required" //Have you studied with us before
},
messages: {
studiedBefore: "Please indicate whether you have studied with us before."
}
});
Each form has an ID and validation for all the forms is in one JS file.
Not that it really matters, but the navigation is in <ul id="tabNav">
Any help much appreciated.
Thanks,
Phil
Check the .valid() method it provides. If you call that in click handlers attached to your links, you should be ok.

CKEditor: Strange Characters after ajax submit

I am using ajax to gather the CKEditor content and submit it to the server. Once I look at it after it is submitted, all the html tags < and > have been converted to their html entities. This is not what I want, as I obviously need to preserve the HTML.
Is there something I did wrong?
A couple of questions:
Which AJAX library are you using?
What method are you using to fetch the content from CKEditor?
I use jQuery + validate (form validation plugin) for my form submissions.
The textarea to which CKEditor is bound is named body.
For some weird reason when I submitted the form, the content wasn't being submitted at all. Looking into the HTML I found that the textarea wasn't being populated by CKEditor (don't ask me why).
What I did was to just prior to submission, manually grab the data from CKEditor and stash it into the textarea. A single line of jquery should suffice.
$( '#body' ).val( CKEDITOR.instances.body.getData() );
And then proceed with the form submission normally. jQuery has a very good data serialization method - a function called serialize(), which I use to convert the entire form's data into a string. At the PHP end, this string is auto-converted into members of the $_POST array.
You should try the same approach and see if it works for you.
If you're still stuck, post your code here.
Cheers,
m^e
In the end I realized that my server was not saving the data at UTF-8 even though ajax was sending it this way. So, I fixed that and the data saves correctly.
Correct is to set up in config this
entities : false

Resources