Manually bind JQuery validation after Ajax request - asp.net-mvc-3

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.

Related

wicket: how to update a form component with ajax, not the whole form

I've got a wicket dropdown choice, and when I select something, I want to update some components within the form. This is working fine using wicket (1.4) ajax. However, it's updating the whole form including the dropdownchoice itself. There are quite a lot of items in the dropdown list (maybe 2000) so it's not great from a performance point of view.
Here's the page hierarchy:
form (Form)
|----packageDDC (DropDownChoice)
|----pptview (RefreshingView)
|----buy (Button)
packageDDC.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
//--snip-- update pricepoints which back up the pptview
target.addComponent(form); //ie the form
}
}
In the ajax debug window I can see all the dropdown choice options being re-sent every time
What I want to do is only update the pptview and the Button via ajax, not the contents of the dropdownchoice.
I tried adding pptview to the target, but it complains that RefreshgViews can't be updated via ajax.
I tried wrapping the pptview with an EnclosureContainer, but wicket didn't like that either (something about setRenderBodyOnly)
So I tried using an WebMarkupContainer (called 'pptcontainer') and setting pptview to be a child of that - but now the pptview is not updated. Instead it says (in Ajax debug):
"ERROR: Wicket.Ajax.Call.processComponent: Component with id [[purchaseButton2f]] was not found while trying to perform markup update. Make sure you called component.setOutputMarkupId(true) on the component whose markup you are trying to update."
"ERROR: Wicket.Ajax.Call.processComponent: Component with id [[pptcontainer2e]] was not found while trying to perform markup update. Make sure you called component.setOutputMarkupId(true) on the component whose markup you are trying to update."
well these objects definitely do have this set to true:
buy.setOutputMarkupId(true);
pptcontainer.setOutputMarkupId(true);
pptcontainer.setOutputMarkupPlaceholderTag(true);
So the page is not updated correctly.
What am I doing wrong?
The new hierarchy is:
form (Form)
|----packageDDC (DropDownChoice)
|----pptcontainer (WebMarkupContainer)
| |----pptview (RefreshingView)
|----buy (Button)
I faced same problem with popup window which content is provided by ajax call. In my case the problem was solved by changing html placeholder "wicket:container" to "div" element as proposed in this article: http://sha.nnoncarey.com/blog/archives/36
After this change generated html has correct id and wicket do not have problem to find it and replace content with AJAX response.

MVC3 Razor Ajax partial page validation

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?

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.

jQuery Showing an Ajax loader during transmission & Prevent Multiple Submits

I have an app that has several different types of form elements which all post data to the server with jQuery AJAX.
What I want to do is:
Show a loader during AJAX transmission
Prevent the user from submitting twice+ (clicking a lot)
This is easy to do on a one off basis for every type of form on the site (comments, file upload, etc). But I'm curious to learn if that is a more global way to handle this?
Something that's smart enough to say:
If a form is submitting to the server and waiting for a response, ignore all submits
Show a DISABLED class on the submitted / clicked item
Show a loading class on the class="spinner" which is closest to the submit item clicked
What do you think? Good idea? Done before?
Take a look at the jQuery Global Ajax Event Handlers.
In a nutshell, you can set events which occur on each and every AJAX request, hence the name Global Event Handlers. There are a few different events, I'll use ajaxStart() and ajaxComplete() in my code sample below.
The idea is that we show the loading, disable the form & button on the ajaxStart() event, then reenable the form and hide the loading element inside the ajaxComplete() event.
var $form = $("form");
$form.ajaxStart(function() {
// show loading
$("#loading", this).show();
// Add class of disabled to form element
$(this).addClass("disabled");
// Disable button
$("input[type=submit]", this).attr("disabled", true);
});
And the AJAX complete event
$form.ajaxComplete(function() {
// hide loading
$("#loading", this).hide();
// Remove disabled class
$(this).removeClass("disabled");
// Re-enable button
$("input[type=submit]", this).removeAttr("disabled");
});
You might need to attach to the ajaxError event as well in case an AJAX call fails since you might need to clean up some of the elements. Test it out and see what happens on a failed AJAX request.
P.S. If you're calling $.ajax or similar ($.getJSON), you can still set these events via $.ajaxStart and $.ajaxComplete since the AJAX isn't attached to any element. You'll need to rearrange the code a little though since you won't have access to $(this).
I believe you have to do 2 for sure and 3 to improve usability of your app. It is better to keep backend dumb but if you have a security issue you should handle that too.

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