I have a customValidator with validation on both the client and server.
Here is the markup:
<input id="theDate" runat="server" />
<br />
<asp:CustomValidator ID="valValidateDate" runat="server"
ClientValidationFunction="checkDate"
ControlToValidate="theDate"
ValidateEmptyText="True" >Error Message Text</asp:CustomValidator>
My client side validation function is simple. It just sets it the field to not valid.
function checkDate(src, args) {
args.IsValid = false;
//alert(args.IsValid);
return false;
}
I think this should stop the postBack but it does not.
If I uncomment that alert I see that the value is false - and that stops the postBack. In fact, having the alert alone stops the postback.
With the alert, which stops the postBack, I see the error message as long as I set args.IsValid to false - even without a return = false.
How do I stop the postback when the clientside validation fails?
I'm using:
firefox and chrome
Visual Studio 2010
Asp.Net webForms - framework 4.0.3
Related
I started noticing this problem after my session expired and I would click a button to perform an Ajax Postback inside of an UpdatePanel. ASP would catch the expired session and redirect me to the home page, however the URL it sends me to is escaped and ASP would refuse the request
Url: %2fDefault.aspx%3fReturnUrl%3d%252fMyPage.aspx%253fCurrentDate%253d2013-04-19%26CurrentDate%3d2013-04-19.
Error: The request filtering module is configured to deny a request that contains a double escape sequence.
To narrow the problem I setup a test case of Postbacks inside and outside of an UpdatePanel.
Test.aspx:
<asp:UpdatePanel runat="server" ID="upTest">
<ContentTemplate>
<asp:LinkButton runat="server" ID="lnkAjaxPostbackTest" OnClick="PostbackTest">AJAX Postback Test</asp:LinkButton><br />
<asp:LinkButton runat="server" ID="lnkAjaxPostbackRedirectTest" OnClick="PostbackRedirectTest">AJAX Redirect Test</asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
<asp:LinkButton runat="server" ID="lnkPostbackTest" OnClick="PostbackTest">Postback Test</asp:LinkButton><br />
<asp:LinkButton runat="server" ID="lnkPostbackRedirectTest" OnClick="PostbackRedirectTest">Redirect Test</asp:LinkButton>
Test.aspx.cs
protected void PostbackTest(object sender, EventArgs e) {
var x = 3;
}
protected void PostbackRedirectTest(object sender, EventArgs e) {
Response.Redirect("~/Default.aspx");
}
Results
The regular (non-Ajax) postbacks worked correctly in all cases (even when the session expired). However, the AJAX Redirect Test would send me to /%2fDefault.aspx when my session was active and the AJAX Postback Test would send me to /%2fDefault.aspx%3fReturnUrl%3d%252fTest.aspx if the session expired.
So why is this happening? Perhaps javascript is handling the redirect and it isn't performing decodeURIComponent? I couldn't find anything in the HTTP response that indicates that a redirect should occur.
The culprit is the ToolkitScriptManager in the AjaxControlToolkit assembly. I replaced it with the regular ScriptManager provided in ASP and the problem instantly vanished.
In summary: AjaxControlToolkit.ToolkitScriptManager + Ajax Postback + Redirect => Doubly Escaped Uris
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"
Client side Validation and ValidationSummary is working fine for my project (MVC4 + Razor + Unobtrusive JS) but the Server side errors are not shown on my view and if there was any client side error, it does not get removed from the view (it does from the ModelState). I have tried on both Chrome14 and IE9
Server side errors are being added to the model as ModelState.AddModelError(string.Empty, ModelState.AllErrors()); and shown to the view as #Html.ValidationSummary(false).
Edit
Simple form submit is working fine, it shows multiple error messages returned from the server and updates error messages, but, ajax based form submit is not working error messages returned by ajax based form submit are not shown at all.
Here is a sample demonstration of how the request is being made
#*... View contents related to Master Model ...*#
#using (Ajax.BeginForm("ActionToAddRecord", new AjaxOptions()))
{
#Html.Action("ActionToAddRecord")
<input type="submit" value="Add Record"/>
}
#*... View contents related to Master Model ...*#
ActionToAddRecord is a partial view representing a model contained by a master model
Errors are returned as
[HttpGet]
public ActionResult ActionToAddRecord()
{
return View();
}
[HttpPost]
public ActionResult ActionToAddRecord(childModel model)
{
ModelState.AddModelError(string.Empty, "First error message");
ModelState.AddModelError(string.Empty, "Second error message");
return View(model);
}
Edit
I saw a similar functionality in templated MVC application by VS2010, the dialog based log in form. Error messages are returned as Json and then JS is being used to display them, IMO, seems like MS made Ajax based requests quite easy and concise (Ajax.BeginForm) but missing the error handling part. Right now i am not willing to use JS for this, there might be a better way to get this type of error handling dealt automatically.
Solved, with a small error.
Master View
#*Master View Contents*#
#using (Ajax.BeginForm("AddPaymentCurrency", new AjaxOptions { UpdateTargetId = "paymentCurrency" }))
{
<div id="paymentCurrency">
#{Html.RenderPartial("PaymentCurrency", Model.PaymentCurrencyNew);}
</div>
}
PaymentCurrency View
#*Model Editors*#
#Html.ValidationSummary(false)
<input type="submit" value="Add Payment Currency"/>
<div id="paymentCurrencyList" style="width:inherit; height:auto; overflow:auto;">
#Html.Action("PaymentCurrencyList")
</div>
Controller
[HttpPost]
public ActionResult AddPaymentCurrency(PaymentCurrency model)
{
if (!ModelState.IsValid)
{
ModelState.AddModelError(string.Empty, ModelState.AllErrors());
return View("PaymentCurrency", model);
}
//Add login
return View("PaymentCurrency", model);
}
public ActionResult PaymentCurrencyList()
{
//var list = getList
return View(list);
}
small error
ValidationSummary is shown with fields highlighted and asterisk shown against them while adding invalid payment currency. Once a valid currency is added then ValidationSummary and asterisk is no more shown on invalid payment currency, just fields are highlighted.
Please help me to get it fixed, i would prefer not to change the current structure, otherwise i will start getting big error
I have a form with validators and 2 buttons inside form:
<input type="submit" class="LFL_btn" value="" />
<input type="image" src="/Content/images/btn_register.jpg" class="LFR_btn" id="btnRegister" />
but validator works and for second button too. Why and how to fix it?
Why?
Because jquery.validate kicks in when you submit a form by hijacking the submit event of this form. And since both are submit buttons, validation is run for both of them.
how to fix it?
Add class="cancel" to the button you want to exclude from validation which will instruct the jQuery.validate plugin not to run validation:
<input type="image" src="/Content/images/btn_register.jpg" class="LFR_btn cancel" id="btnRegister" />
<input type="image" src="/Content/images/btn_register.jpg" class="LFR_btn cancel" id="btnRegister" />
This has been covered in the documentation.
Obviously all this refers only to client side validation. On the server it's a whole different story. If you wanted to disable validation when some button is clicked you will first need to know which button was clicked. This could happen by giving the first button a name attribute and then inspecting on the server the value of this parameter from the request:
<button type="submit" class="LFL_btn" name="validate" value="validate">Validate</button>
and then inside your controller action check if this button was used to submit the form and apply validation only in this case:
[HttpPost]
public ActionResult Foo(string validate)
{
if (!string.IsNullOrEmpty(validate))
{
// the Validate button was clicked:
var model = new MyViewModel();
if (!TryUpdateModel(model))
{
// there were validation errors => redisplay the view
return View(model);
}
// validation went fine => do some processing...
}
else
{
// the image button was clicked
// do some other processing ...
}
}
I've faced the following problem. I'm developing a form for the site and this form should have validation. I wanna to use native ASP.NET MVC 2 validation functionality but get stubborn with it. I have a form that is loaded via $.get and displayed using jQuery UI modal dialog. All examples I found explains how to use MVC validation with simple forms and avoid Ajax forms.
I can enable client side validation for this form, but I need to handle server-side validation correctly. How can I handle server-side validation model errors for ajax forms?
When you pass your object back to the controller, you have to wrap your code in If ModelState.IsValid
Below is a simplified version of how I edit a user. The first "EDIT" sends the User object TO the View. The second "EDIT" handles the post from the view.
Function Edit() As ActionResult
''# do stuff to populate your User
Return View(User)
End Function
<AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal user as User)
If ModelState.IsValid Then
''# do your valid stuff
Else
''# The posted form was not valid, send the user back
Return View(user)
End If
End Function
Here's the same thing in C#
public ActionResult Edit()
{
// do stuff to populate your User
return View(User);
}
[AcceptVerbs(HttpVerbs.Post)]
public object Edit(User user)
{
if (ModelState.IsValid) {
// do your valid stuff
} else {
//'# The posted form was not valid, send the user back
return View(user);
}
}
EDIT:
On your view, if you want to add AJAX validation, just add the following.
<%
Html.EnableClientValidation() ''# This is where all the magic happens. It will build your clientside validation for you out of your MetaData.
Using Html.BeginForm("Edit", "Users")
%>
<!-- all your markup crap -->
<tr>
<td>
<%: Html.LabelFor(Function(model) model.UserName)%></td>
<td>
<%: Html.TextBoxFor(Function(model) model.UserName) %>
<%: Html.ValidationMessage("UserName", "*")%><br />
</td>
</tr>
<!-- somewhere you'll want to add a Validation Summary of all your errors -->
<%= Html.ValidationSummary("Oops!, please correct the errors...") %>
<% End Using%>
<!-- bottom of the page -->
<script src="../../Assets/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Assets/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Assets/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
EDIT:
Here is some info on rendering using Ajax.BeginForm
http://singulartechnologies.com/asp-net-mvc-ajax-beginform-sample-code
http://msdn.microsoft.com/en-us/library/dd381533.aspx
http://weblogs.asp.net/mikebosch/archive/2008/02/15/asp-net-mvc-submitting-ajax-form-with-jquery.aspx