How to display a name after successful remote validation? - asp.net-mvc

My business web application will have a lot of input controls where the user is expected to enter some kind of code (Country, Zip, Employee ID, etc.).
I'm using RemoteAttribute to validate code entries against my database to ensure that users entered the correct code.
The thing is, my standard feature should be to display a name of entered code if the remote validation is successful or error if the validation is not successful.
I'm not sure how to do this.
The obvious answer is to send Name property along with true value in Json object which jquery unobtrusive validation requires. The cshtml could look something like this:
#Html.LabelFor(m => m.Country)
#Html.EditorFor(m => m.Country, new { data-codename-label="lbnCountry" })
<label ID="lbnCountry"></label>
I'm not sure how to implement such an idea though. Any help is appreciated.

Take a look at this answer which should work for you as well.
Do something on success response for remote validation in mvc
If in that example you choose not to send your value through the custom response header, you can always modify the javascript to do an ajax call to an action/webapi that will return the value in question after a successful validation.

Related

Difference between 'Html.Validate' and 'Html.ValidateFor'

Why do we use .Validate and .Validatefor in validation?
I am using that, but I am not getting any error message in the UI.
Code
<div>
#{Html.BeginForm();}
#Html.TextBoxFor(x => x.LastName, new { id = "txtLastName" })
#{Html.Validate("LastName");}
#{Html.ValidateFor(x=>x.LastName);}
<input type="submit" id="btnSubmit" value="Submit" />
#{Html.EndForm();}
</div>
This behavior is intentional. Both these helpers just register corresponding parameters for client-side validation, without actually showing any message should the validation fail. However this message can still be displayed in a ValidationSummary.
If you want to show the message specific to the field/parameter, you should use ValidationMessage or ValidationMessageFor instead:
#Html.ValidationMessage("LastName")
#Html.ValidationMessageFor(x=>x.LastName)
If there are situations where you don't actually want a validation message to visually appear for each field (i.e. by using Html.ValidationMessage), but would rather allow a summary to be the sole source of validation error messages (i.e. by using Html.ValidationSummary), you still need some way to "trigger" the validation to occur for the specific fields you want it to. This can be achieved by using the Html.Validate/Html.ValidateFor<> methods within your view. Those helpers won't render anything, but will simply register the specified field for client-side validation.
See this post for answer How does validation in ASP.NET MVC 2 actually work?

ASP.NET MVC3 Custom Unobtrusive Client Side Validation not preventing Ajax form post

I have a "change password" page that needs to hash any passwords entered on the page via Javascript before sending. To complicate it, the page is loaded via a jQuery load() call, and is submitted by a jQuery.Form ajaxForm() call. Had everything working in MVC2, but MVC3 is giving me trouble.
That is, I have a page with a "Change Password" link that when clicked, loads the change password page into a jQuery modal popup, then the form on the change password page get's submitted via the jQuery.Form library (Essentially just wraps a $.ajax call), and returns it's result into the modal same modal popup.
Essentially, I have a model with two properties, OldPassword and NewPassword. I have two hidden fields generated by by view for these. They hold the hashed value of two other fields, PrehashOldPassword and PrehashNewPassword, and get updated via keyup events (I know, this means it does a whole SHA256 hash on every keyup... inefficient, but got the job doen for testing). The key here is that the regex validation and required field validation needs to be executed on these Prehash fields, which exist on the client side only (As obviously I don't want to transmit these fields to the server in any way).
So I manually create these two and add on the data-val-* attributes to the elements, i.e. they are NOT generated by the MVC helpers, etc. I am guessing that this is where I'm missing something. When the form submits with all fields empty, all of the errors popup that should, but the form goes right ahead and submits anyway.
==
So the things I've tried:
Yes, the unobtrusive library parse() method already get's called to parse the AJAX loaded form contents, and it appears to get all of the data validation stuff correctly, since I see the errors show up as fields blur(), and when I hit submit (before the ajax request completes and replaces the content of the popup).
Possible note: this call to the unobtrusive library's parse method happens AFTER the AJAX successfully loads the change password page into the popup... the AJAX form submit binding is put on document.ready of the loaded content, ergo, the AJAX form submission binding MAY be binding prior to, and thus firing before, the validation calls that the parse method may bind to the submit event...
However, (1) I am doing this same sort of thing in other places without issue, the ONLY DIFFERENCE being that I am manually putting these data-val-* attributes on elements I am creating manually! And (2), if I cause some kind of error on the OldPassword or NewPassword fields, i.e. a required field validation error by not loading a value into them, they display their error, and successfully STOP the form from submitting through the jQuery.Form method.
So I think something has to be wrong here:
<input id="PrehashNewPassword" type="password" name="PrehashNewPassword" data-val-required="The password field is required." data-val-regex-pattern="<%= RegexHelper.PasswordRegularExpression %>" data-val-regex="<%= RegexHelper.PasswordRegularExpressionError %>" data-val="true" />
I know that jquery.validate is getting the rules right, since I DO see the errors. It's just not stopping the form from submitting when their is an error in these manually generated elements, unless I do something like this, and add a pre-submit callback on the form's AJAX submission:
$("#ChangePasswordForm").ajaxForm({
beforeSubmit: function () { if (!$('#ChangePasswordForm').valid()) { return false; } },
target: '#overlay'
});
While this works, it is kind of ugly and I believe it causes the validation to be called twice... Not a huge deal, but less than ideal. So is there some other call that I need to make in the unobtrusive library to bind these?
Not sure if you found the problem, but you may try to
return false
in there if the form is not valid...
.
.
.
if (!$('form').valid()) {
return false;
}
// JSON POST...
.
.
.
If that doesn't work, then you could try to use:
$.validator.unobtrusive.parse($("#dynamicData"));
after dynamically adding your custom inputs. "dynamicData" is the ID of an element wrapped around the form
above found from here: http://weblogs.asp.net/imranbaloch/archive/2011/03/05/unobtrusive-client-side-validation-with-dynamic-contents-in-asp-net-mvc.aspx
Out of interest, what happens if you just get the form to validate?
<script type="text/javascript">
$("form").submit(function (evt) {
// validate here should trigger invalid fields
$('form').valid();
// JSON POST...
// stop form submitting
evt.preventDefault();
});
</script>

How to do in-line form validation of multi-field business rules (repository) in MVC?

There is a study here my co-worker took to my notice. Basically, that in-line form validation is a good thing.
But how would you do in-line multi-field form validation in MVC assuming you already have a "yield return" setup to return a list of form violations? Is the in-line validation only for primitive values like "a zip code should not include alpha characters?"
Would you submit some Javascript code to the client that checks that "this field and this field should be evaluated together firing this validation, and oh by the way, we are going to validate all fields again on a final submit?
Anyone have code example (C# and MVC) to illustrate handling in-line multi-field form validation using a remote repository (but not all fields at one time)?
I don't have any code but if I was going to do inline validation I would implement the validation sample in Nerd Dinner.
Clearly this would validate on a submit so not really useful to your question. However, if you couple it with jQuery then it does become useful.
Essentially I'd be doing a jQuery postback at key points, checking for validation errors, and then highlighting the errors to the user in the callback.
You can attach events to say the lost focus events of fields that have a certains style class or to all fields etc. Really quite extensible in that regard.
There are tons or samples on jQuery and how to post back etc.
I'd also still be doing the full validation check on postback as well just to catch anything that may have been missed.
Does this help?

How does validation in ASP.NET MVC 2 actually work?

I am trying to trace through why my ASP.NET MVC 2 validation isn't working, but I cant find enough about HOW it works to be able to do this.
I have followed the steps in this useful article by David Hayden which seems to be the best documentation currently out there, but nothing actually happens.
I get validation when i submit to the server (as I did since Preview 1 when i added data annotations to my model) but I'm not getting any client side validation.
How can i trace through to test? So far I have verified the following obvious things
MicrosoftMvcJQueryValidation.js and jquery.validate.min.js files are being downloaded
Html.ClientValidationEnabled = true
I cant see easily what is hooking up to which events to know quite how to debug it.
Here's what I've learnt:
MOST IMPORTANT
Your HTML Form must be created with the using directive, not just BeginForm and EndForm.
You must set Html.ClientValidationEnabled = true BEFORE you start your 'Form'
You must use Html.ValidationMessage for each field
You must set Html.ClientValidationEnabled = true on each partial control (ascx)
HOW IT WORKS (very simple overview)
When you do Html.BeginForm it creates a 'FormContext' in the ViewContext
When ValidationMessage helpers are used, metadata is put into the form context
When the form is disposed (by the using statement) it writes out all the validation code
MISC
I cannot seem to get validation working when I have a partial control, if that control uses a different model from the view that defines the Form.
You do NOT need to use Html.TextBoxFor or Html.ValidationMessageFor, you can use Html.TextBox and Html.ValidationMessage
In order for a field to be validated client-side you have to specify a call to Html.ValidationMessage/Html.ValidationMessageFor<> for the field (just like David did in the tutorial you linked) within the view. This is essentially a trigger to the client-side validation logic that you want to run validation for that field.
If there are situations where you don't actually want a validation message to visually appear for each field (i.e. by using Html.ValidationMessage), but would rather allow a summary to be the sole source of validation error messages (i.e. by using Html.ValidationSummary), you still need some way to "trigger" the validation to occur for the specific fields you want it to. This can be achieved by using the Html.Validate/Html.ValidateFor<> methods within your view. Those helpers won't render anything, but will simply register the specified field for client-side validation.
Both of those requirements exist since you might not want the client-side validation to automatically validate every property on your model object, since some of them might not even be part of the form that you're wanting validated.

How do I turn off validation on Html.DropDownList() when using an option label?

I am passing a optionLabel into the Html.DropDownList helper (taken from this SO question):
<%=Html.DropDownList("PO.Vendor.VendorId", this.Model.Vendors, "-- add a new vendor --")%>
That produces markup with an option of value 0 with the text "-- add a new vendor --", which is exactly what I want. However, if that option is selected and posted, a validation error is thrown.
Is there way to turn off this automatic validation when using an optionLabel?
The code snippet that you posted doesn't have anything to do with the validation being performed. You could easily just write out all the options in the list manually and you'd still be getting the validation error.
Without seeing the code that is performing the validation, it's hard to tell you how to turn it off. If you're using the reflection-based "UpdateModel()" like in NerdDinner, you'll need to add some code to remove/change that posted value.
Wherever your validation code is, you'll have to work something out to ignore that value.

Resources