jQuery Validation Problem using MVC 3 - asp.net-mvc-3

My problem is I am using the MVC3's feature of unobtrusive client side validation but I need to hook into it and add a function that fires on a successful validation but before the form is posted.
I'm hoping there is some pre-built helper or an easy way to hook into the validator.
Here's a code snippet:
#using (Html.BeginForm("MyAction","MyController")) {
#Html.ValidationSummary(true)
<fieldset> <legend><legend>
<label for="FirstName">First Name</label>
#Html.TextBoxFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)

try these articles...
http://devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
Is it possible to "hack into" the unobtrusive validaton supported in ASP.NET MVC 3?
hope these help you ...
thanks

I ended up needing to hook into the validation process to perform my own custom validation and also do some div collapsing. Here's a snippet of jQuery that accomplished what I needed:
//Hijack the submit event to do custom validation and collapse the div
$('#theFormName').submit(function () {
var customErrorHandling = false;
//do some custom validation
if (customerErrorHandling == false) {
//Now do the jQuery validation
if ($('#theFormName').valid()) {
//do some div collapsing
$('#theFormName').unbind('submit');
$('#theFormName').submit();
}
}
return false;
});

Related

ASP.NET MVC: OnKeyUp event for Ajax

When I wanna use the OnKeyUp event with AJAX in ASP.NET I have to do:
#using(Ajax.BeginForm("Action", "Controller", new AjaxOptions{... UpdateTargetId = "target"}) {
<div id = "target"></div>
#Html.TextBox ("TextField","", new {#OnKeyUp = "TriggerFunction()"}
<input type="submit" id = "button" style = "display:none"/>
}
Then in JQuery
function TriggerFunction(){
$("#button").trigger("click")
}
Although this works, I'm curious does ASP.NET MVC have any built in feature to do this? I mean trigger the BeginForm method based on different events like OnKeyUp or OnChanged?

MVC3 C# Disabling the Validation Messages on Cancel

I have an MVC2 C# .Net Web App. We are using the built in MVC3 Validation using the Domain class properties [Required(ErrorMessage = "Start From is required.")] and in the HTML #Html.ValidationMessageFor(model => model.StartFrom)
However, when we submit the page using the Cancel button, the validation is fired stating the "Start From is Required" and therefore not exiting the page. How can I disable the Validation on the Cancel button? Or submit the page without firing the Validation?
I think you need to override the default behaviour of the submit button i.e., Cancel button in your case.
Say you have the cancel button like this:
<input type="submit" id="btnCancel" value="cancel"/>
now write the jQuery to override the default behaviour
$(function(){
$('#btnCancel').click(function(e){
e.preventDefault();
//or you can return false from this method.
//return false;
});
});
I found an answer here, on Stackoverflow :) jQuery disable validation
Each of the first two answers in that link worked for me. #Karthik, thanks for the answer. It got me on the right track
Answer 1:
<input id = "theCancel" class="cancel" type="submit" value="Cancel" />
Answer 2:
$(function () {
$('#theCancel').click(function (e) {
$("form").validate().cancelSubmit = true;
});
});
I chose answer 2 and put it in our global js file. All of our Cancel buttons have an id of "theCancel"

How to properly disable an Html Helper Textbox or TextBoxFor?

I have a razor display that is being used for entry. In one case, I would like the user to be able to populate the text box, in the other case, I would like to prevent the user from populating it. I am using code like:
#Html.TextBoxFor(model => model.Goop, new { #class = "text-box", maxlength = 2, onfocus = "javascript:this.select();" })
if (Model.Review.ReviewType.Equals("M"))
{
<script type="text/javascript">
$(function () {
$("#Goop").prop("disabled", true);
});
</script>
}
I have tried to do this several ways, jQuery (above), CSS attribs, javascript, ASP.NET... but all have the same issue: When the form is submitted, if the Goop textbox is disabled, the value for Goop in the model is Null. Ideas?
Thanks in advance!
Maybe it's not as cool without jQuery, but when I do this in my apps I do something along the lines of
if (Model.Review.ReviewType.Equals("M"))
{
#Html.DisplayFor(model => model.Goop)
#Html.HiddenFor(model => model.Goop)
}
else
{
#Html.TextBoxFor(model => model.Goop)
}
If a form element is disabled, it does not post a value. That's how it's supposed to work.
To work around this, you will need to do one of several things. You can enable the fields just before posting by intercepting the submit method. You can use a hidden field to store the data in addition to the disabled control. Or you can just assume the values on the controller side.
by the way, it should be .prop("disabled", "disabled"), which renders as disabled="disabled", that's standards compliant.

Why unobtrusive MVC validations are not working in IE7 and IE8?

I have an application in ASP.NET MVC 3 using Razor. I have setup some data annotations on text boxes along with jQuery validation and unobtrusive validation.
The thing is, some fields have custom validation logic using plain old vanilla JavaScript like the following functions.
function Validation() {
var signUp = SignUpValidation();
var book = BookingValidation();
if (signUp && book) {
return true;
}
else
{
ShowErrorMessage();
return false;
}
}
function ShowErrorMessage()
{
$('span#ErrorMessage').html('These fields are required');
}
where SignUpValidation(), BookingValidation() are functions which
returns either true or false on basis of some other validation
logic.
This is my code for submit button.
#using (Html.BeginForm(MVC.Booking.Actions.AtWork(model: null), FormMethod.Post,
new {#onsubmit = "return Validation()" }))
{
#Html.Partial("_BookingView")
}
This approach is working in all browsers except IE-7/8.
I faced the same issue lately .. and worked out the following solution:
instead of giving your additional form validation (apart from the unobtrusive mvc 3 validation) as a separate/second submit handler in form "onsubmit" event, you should "inject" your additional validation function in the main unobtrusive validation process of mvc3.. let it take care of the rest.
Create a custom validation adaptor somewhere in your common javascript code/file:
(function ($) {
if($.validator && $.validator.unobtrusive) {
$.validator.unobtrusive.adapters.addBool("AdditionalFormValidation");
}
} (jQuery));
In your view file, where you have the form, add this code to create a new jquery validator method for the custom validator adaptor that you defined in your common file above:
(function ($) {
if ($.validator) {
$.validator.addMethod("AdditionalFormValidation", function (value, element) {
return Validation();
});
}
} (jQuery));
Here
- "AdditionalFormValidation" is the validator method name same as your custom validation adaptor.
- "Validation" is the name of your javascript function that takes care of your additional validation and returns a boolean result for validation successs or failure.
In your form, remove the "onsubmit" handler that you had supplied, add a invisible dummy text field to your form and apply the custom unobtrusive validation adaptor/rule that you created, as given below:
#using (Html.BeginForm(MVC.Booking.Actions.AtWork(model: null), FormMethod.Post))
{
#Html.Partial(MVC.Booking.Views._BookForAtWork)
<input type="text" style="visibility:hidden; width: 1px; height: 1px;" name="hiddenValidation" id="hiddenValidation" data-val="true" data-val-AdditionalFormValidation />
}
This solution worked like a charm for me. To me appears a cleaner solution as it injects the additional validation in the same unobtrusive validation flow of mvc3 rather than creating a second validation flow. Also it is inline to future improvement for creating custom data annotation (validations) for all the custom client side validation work.
You may try updating both your jQuery.Validate.min.js and jquery.validate.unobtrusive.min.js files to latest version...it could be that these files are old...I had the same issue some time back and fixed it by doing this update.

ASP.Net MVC 3 validation on AjaxForm

I have an ajax form on razor view engine. For validation i use dataanotation classes. Validation work fine when user submit the form, validation messages work fine.
The problem is, validation wont work on keyup or blur events.
How can i activate validation without submit on ajaxform(ajax.beginform)
Here is my view code:
#using (Ajax.BeginForm(new AjaxOptions { InsertionMode = InsertionMode.Replace,
UpdateTargetId = "employeeDetail", HttpMethod = "Post", OnComplete = "Complete",
Confirm = "Confirm?" }))
{
#Html.TextBoxFor(model => model.Email)
#Html.ValidationMessageFor(model=>model.Email)
<span style="float:right"><input type="submit" class="tableGenelButton" id="submitButton" value="Kaydet" /></span>
}
Model:
[RequiredWithMessage]
[Display(Name = "E-Mail")]
public string Email { get; set; }
Update:
Ok, apparently you're using Ajax.BeginForm which uses MicrosoftAjax in stead of jQuery (I didn't realize that before). This one needs some extra work to enable client side validation:
You need
<% Html.EnableClientValidation(); %>
Somewhere in your page, and also links to MicrosoftAjax.js, MicrosoftMvcAjax.js and MicrosoftMvcValidation.js
Here's a link that might be interesting for you:
ASP.NET MVC Client Side Validation With Ajax.BeginForm
To enable client side validation for a custom validation attribute (I guess [RequiredWithMessage] is one of those), you have to implement the IClientValidatable interface.
Here is an article that explains how to do that:
The Complete Guide To Validation In ASP.NET MVC 3 - Part 2
Assuming you have client side validation enabled, you will need to call .validate() in the relevant events:
$("#theFormToValidate input").blur(function(){
$("#theFormToValidate").validate();
});
and
$("#theFormToValidate input").keyup(function(){
$("#theFormToValidate").validate();
});

Resources