Created
July 25, 2012 22:11
-
-
Save esouto/3179020 to your computer and use it in GitHub Desktop.
mvc: Mvc Razor Forms (Form, BeginForm, data-val-, ViewContext.FormContext)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@{ Html.BeginForm("test", "home", FormMethod.Post, new { @id = "frmUpdate" }); } | |
.... | |
@{ Html.EndForm(); } | |
@using (Html.BeginForm("test", "home", new { Area = "MassProcessing" }, FormMethod.Post, new { @id = "frmUpdate" })) | |
.... | |
@{ Html.EndForm(); } | |
@* | |
For use with <form action: | |
@{ if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext(); } | |
Otherwise your data-val-* attributes will not be emitted by the helper methods. You need this if your views do not have an Ajax.BeginForm or Html.BeginForm to create their own form context. | |
[ http://stackoverflow.com/questions/5825631/asp-net-mvc-can-you-use-data-annotations-validation-with-an-ajax-jquery-cal ] | |
[ http://stackoverflow.com/questions/6657641/asp-net-mvc-3-client-validation-attributes-generation ] | |
Force to emit validation data-val-: | |
If you want the data validation tags to be there, you need to be in a FormContext. Hence, if you're | |
dynamically generating parts of your form, you need to include the following line in your partial view: | |
@{ if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext(); } | |
You then need to make sure you dynamically rebind your unobtrusive validation each time you add/remove items: | |
$("#form").removeData("validator"); | |
$("#form").removeData("unobtrusiveValidation"); | |
$.validator.unobtrusive.parse("#form"); | |
*@ | |
<form action="@Url.Action("test", "home")" method="post" id="frmUpdate"> | |
.... | |
</form> | |
@using (Html.BeginForm()) | |
.... | |
@{ Html.EndForm(); } | |
@using (Html.BeginForm("test", "home", FormMethod.Post, new { @id = "frmUpdate" })) | |
{ | |
.... | |
} | |
<script type="text/javascript"> | |
function validateAjaxForm() { | |
$("form").removeData("validator"); | |
$("form").removeData("unobtrusiveValidation"); | |
$.validator.unobtrusive.parse("form"); | |
return $("form").valid(); | |
} | |
</script> | |
@{ Html.EnableClientValidation(true); } | |
@using (Ajax.BeginForm("Step", "Origination", new AjaxOptions { UpdateTargetId = "stepArea", OnBegin = "return validateAjaxForm();" }, new { id = "form" })) | |
{ | |
<div id="stepArea"></div> | |
<input id="btnSubmit" type="submit" value="submit" /> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment