Skip to content

Instantly share code, notes, and snippets.

@esouto
Created July 25, 2012 22:11
Show Gist options
  • Save esouto/3179020 to your computer and use it in GitHub Desktop.
Save esouto/3179020 to your computer and use it in GitHub Desktop.
mvc: Mvc Razor Forms (Form, BeginForm, data-val-, ViewContext.FormContext)
@{ 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