Asp.net Mvc3 ads some custom attributes like "data-val-required" on input elements to perform validation. I know all theory behind this, how it works.
What i want to know is :
When I create my form inside " #using (Html.BeginForm())" it produces custom attributes, but it doesn't create those attributes when i place my form between plain "<form>" tag.
below is a demo i have created to demonstrate what iam saying
Razor Code, form inside BefingForm()
#using (Html.BeginForm()) {
#Html.EditorFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress)
}
generated Html contains "data-val-required" as attribute shown below
<input type="text" value="" data-val-required="The Email Address field is required." data-val-email="my message">
Razor Code Form inside pure Html Tag
<form action="/Account/Register" method="post">
#Html.EditorFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress)
</form>
generated Html doesnt contain "data-val-required" attribute shown below
<input type="text" value="" gtbfieldid="44">
My question is how can i ask MVC to add those attributes even form is placed in side pure html tags
I believe BeginForm method internally assigns a formcontext object to viewCotnext's property FormContext. If you do not want to use plain html form tags you have to do it manually like
<%
this.ViewContext.FormContext = new FormContext();
%>
and in razor it would probably be
#{
this.ViewContext.FormContext = new FormContext();
}
Problem here is that internally Html.BeginForm is flagged by Html.EnableClientValidation() to create FormContext that will store client-side validation metadata. Now, any HTML helper method that renders validation message also registers appropriate client-side validation metadata in FormContext. The result is what you get if you use helper. However, if you try to use HTML syntax and not helpers, the FormContext is never registered and therefore your validation is never added.
Regards,
Huske
I want to use jQuery ($.post) to submit my html form, but I want to use the client side validation feature of MVC 2. Currently I hook up the post function to the "OnSubmit" event of the form tag, but I can't hook into the validation, ideally I want to be able to do
if (formIsValid) {
$.post('<%=Url.Action("{some action}")%>'...
}
Please note, Client side validation is working with jQuery.validation, I just can't get it to test if the validation was successful or not before I post my data.
Andrew
The final solution
<%
Html.EnableClientValidation();
using (Html.BeginForm("Register", "Account", FormMethod.Post, new { id = "registrationForm" })) {
%>
...
<button type="submit" onclick="return submitRegistration();">Register</button>
<%
}
%>
<script type="text/javascript">
function submitRegistration() {
if ($("#registrationForm").valid()) {
$.post('<%=Url.Action("{some action}")'...
}
// this is required to prevent the form from submitting
return false;
}
</script>
You can initiate jQuery validation on the button click event. Place the following inside your button-click event-handler:
if ($('form').valid())
//take appropriate action for a valid form. e.g:
$('form').post('<%=Url.Action("{some action}")%>')
else
//take appropriate action for an invalid form
See the Validation plugin documentation for more information.
I have setup a simple example to show a form inside a jquery UI dialog and wish to enable inline client side validation on that form
I have then added the scripts to my master page
<script type="text/javascript" src="<%: Url.Content( "~/_assets/js/jquery-1.4.3.min.js" )%>"></script>
<script type="text/javascript" src="<%: Url.Content( "~/_assets/js/jquery.validate.min.js" )%>"></script>
<script type="text/javascript" src="<%: Url.Content( "~/_assets/js/MicrosoftMvcJQueryValidation.js" ) %>"></script>
and then I have enabled Client Side Validation through the following code
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm() { %>
<% } %>
Then, I dont know how to enable inline validation for every input so when the user leaves the focus from any of them validation occurs.
The client side validation seems to work only after I have done a submit. But that is not a "client side validation" as the attributes get validated from my server code...
Any suggestion?
Finally I have got through the solution.
First of all, my forms were never binded to validation callbacks provided by the code inside the MicrosoftMvcJQueryValidation.js script. This because I am using jQuery dialogs and the form is inside the dialog while the script included in the master page.
My first attempt toward the solution has been to modify the MicrosoftMvcJQueryValidation.js. In particular I have added a function EnableClientSideValidation() where I moved the code that was in the $(document).ready function as in the following code sample
function EnableClientSideValidation() {
var allFormOptions = window.mvcClientValidationMetadata;
if (allFormOptions) {
while (allFormOptions.length > 0) {
var thisFormOptions = allFormOptions.pop();
__MVC_EnableClientValidation(thisFormOptions);
}
}
}
$(document).ready(function () {
EnableClientSideValidation();
});
Then I have called the same function inside a script block that I have placed in the dialog markup code $(document).ready() function
With the help of firebug I have placed a breakpoint inside the EnableClientSideValidation() function and then experienced the fact that was called only when the main page was ready but not from the dialog. This was due to the fact that I had my "dialog" script block inside the <form>...</form> tag and so the script did not worked.
Code like this
<% using (Html.BeginForm()) { %>
//DIALOG FORM CODE WAS HERE
<script type="text/javascript">
$(document).ready(function () {
EnableClientSideValidation();
});
</script>
<% } %>
has been changed to
<% using (Html.BeginForm()) { %>
//DIALOG FORM CODE WAS HERE
<% } %>
<script type="text/javascript">
$(document).ready(function () {
EnableClientSideValidation();
});
</script>
Finally everything started working! I would like to thanks vandalo and kdawg for helping in finding a solution. There was something still missed but your answers have stimulated my head.
I am posting this for other that can have the same problem.
OK, so here's what I did to get MicrosoftMvcJQueryValidation to work for me in an AJAX/PartialView environment. It's relevant, because essentially both instances (my AJAX/PartialView stuff and your onBlur triggering) require explicit control of when the validation methods are called. I'll try my best to capture everything you need to do, because I ended up having to edit my MicrosoftMvcJQueryValidation.js file to get it AJAX-enabled. However, I don't believe any of my edits are required for what you want.
The key lies in being able to access the validation functions that MicrosoftMvcJQuery generates. Fortunately, it adds it to the form element via a property called validationCallbacks.
In my custom submit function, I access and call these callbacks like this (form is the DOM element, not a jQuery object):
// this taps into the mvc clientside validation functionality.
// this is a roundabout way of calling jquery.validate() as
// that is what's going on the in callback() function
validationCallbacks = form.validationCallbacks;
if (validationCallbacks) {
for (i = 0; i < validationCallbacks.length; i += 1) {
callback = validationCallbacks[i];
if (!callback()) {
// subsequent submit handlers should check for
// this value before executing
event.cancelBubble = true;
return false;
}
}
}
I then have my context-specific submit functions check event.cancelBubble before continuing.
For your case, you could have this code be called on the blur event for each input in your form. Granted, it's not the most efficient solution, as each function in the validationCallbacks array validates the entire form, but it will trigger validation on each blur. (validationCallbacks is an array to support multiple forms that require validation.)
Sorry it's not super specific to your situation, but it should get what you need.
I have my earlier answer about how to manually call the validation callbacks created by MicrosoftMvcJQueryValidation.js, however, there may be a simpler answer. (I'm leaving my first answer as future reference for anyone.)
The options for jQuery's Validation plug-in give you the ability to change which event triggers validation. From http://docs.jquery.com/Plugins/Validation/validate#toptions, we have the following option properties: onsubmit, onfocusout, and onkeyup. You should be able assign these options values appropriately and have jQuery Validation behave like you want.
You MAY need to tweak MicrosoftMvcJQueryValidation.js to allow for the setting of options for when it calls validation. I had to do that with my edited copy.
You can follow this example:
There's a problem with the script in MicrosoftMvcJQueryValidation.js which must be updated.
Change the script MicrosoftMvcValidation.js in the step 3.
Model:
Namespace Models
Public Class Customer
Private _Name As String = ""
<DisplayName("Name")> _
<Required(ErrorMessage:="{0}: Mandatory field.")> _
<StringLength(10, ErrorMessage:="{0}: Max lenght 10.")> _
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Private _Surname As String = ""
<DisplayName("Surname")> _
<Required(ErrorMessage:="{0}: Mandatory field.")> _
<StringLength(10, ErrorMessage:="{0}: Max lenght 10.")> _
Public Property Surname() As String
Get
Return _Surname
End Get
Set(ByVal value As String)
_Surname = value
End Set
End Property
End Class
End Namespace
<%# Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of MvcApplication1.Models.Customer)" %>
<%# Import Namespace="MvcApplication1.jQuery" %>
...
<% Html.EnableClientValidation()%>
<% Using (Html.BeginForm())%>
<fieldset id="FormEditSet">
<div>
<div>
<%=Html.LabelFor(Function(m) m.Name)%>
<%=Html.EditorFor(Function(m) m.Name)%>
<%=Html.ValidationMessageFor(Function(m) m.Name, "*")%>
</div>
<div>
<%=Html.LabelFor(Function(m) m.Surname)%>
<%=Html.EditorFor(Function(m) m.Surname)%>
<%=Html.ValidationMessageFor(Function(m) m.Surname, "*")%>
</div>
</div>
</fieldset>
<input type="image" src="<%=Url.Content("~/Content/Images/page_save_big.png")%>"
value="Save" title="Save" style="border: none;" />
<%End Using%>
Html.ValidationSummaryJQuery is a new extension method you have to define (follow the example).
Remember to put the script at the bottom of the page:
<script src="<%=Url.Content("~/Scripts/MicrosoftAjax/MicrosoftMvcJQueryValidation.min.js")%>" type="text/javascript"></script>
You need to bind your input fields to properties in your controller, then use the Required attribute on your properties - see http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx for an example.
Now I've seen some questions like this, but it's not exactly what I want to ask, so for all those screaming duplicate, I apologize :).
I've barely touched ASP.NET MVC but from what I understand there is no ViewState/ControlState... fine. So my question is what is the alternative to retaining a control's state? Do we go back to old school ASP where we might simulate what ASP.NET ViewState/ControlState does by creating hidden form inputs with the control's state, or with MVC, do we just assume AJAX always and retain all state client-side and make AJAX calls to update?
This question has some answers, Maintaining viewstate in Asp.net mvc?, but not exactly what I'm looking for in an answer.
UPDATE: Thanks for all the answers so far. Just to clear up what I'm not looking for and what I'm looking for:
Not looking for:
Session solution
Cookie solution
Not looking to mimic WebForms in MVC
What I am/was looking for:
A method that only retains the state on postback if data is not rebound to a control. Think WebForms with the scenario of only binding a grid on the initial page load, i.e. only rebinding the data when necessary. As I mentioned, I'm not trying to mimic WebForms, just wondering what mechanisms MVC offers.
The convention is already available without jumping through too many hoops. The trick is to wire up the TextBox values based off of the model you pass into the view.
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult CreatePost()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreatePost(FormCollection formCollection)
{
try
{
// do your logic here
// maybe u want to stop and return the form
return View(formCollection);
}
catch
{
// this will pass the collection back to the ViewEngine
return View(formCollection);
}
}
What happens next is the ViewEngine takes the formCollection and matches the keys within the collection with the ID names/values you have in your view, using the Html helpers. For example:
<div id="content">
<% using (Html.BeginForm()) { %>
Enter the Post Title: <%= Html.TextBox("Title", Model["Title"], 50) %><br />
Enter the Post Body: <%= Html.TextArea("Body", Model["Body"]) %><br />
<%= Html.SubmitButton() %>
<% } %>
</div>
Notice the textbox and textarea has the IDs of Title and Body? Now, notice how I am setting the values from the View's Model object? Since you passed in a FormCollection (and you should set the view to be strongly typed with a FormCollection), you can now access it. Or, without strongly-typing, you can simply use ViewData["Title"] (I think).
POOF Your magical ViewState. This concept is called convention over configuration.
Now, the above code is in its simplest, rawest form using FormCollection. Things get interesting when you start using ViewModels, instead of the FormCollection. You can start to add your own validation of your Models/ViewModels and have the controller bubble up the custom validation errors automatically. That's an answer for another day though.
I would suggest using a PostFormViewModel instead of the Post object, but to each-his-own. Either way, by requiring an object on the action method, you now get an IsValid() method you can call.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreatePost(Post post)
{
// errors should already be in the collection here
if (false == ModelState.IsValid())
return View(post);
try
{
// do your logic here
// maybe u want to stop and return the form
return View(post);
}
catch
{
// this will pass the collection back to the ViewEngine
return View(post);
}
}
And your Strongly-Typed view would need to be tweaked:
<div id="content">
<% using (Html.BeginForm()) { %>
Enter the Post Title: <%= Html.TextBox("Title", Model.Title, 50) %><br />
Enter the Post Body: <%= Html.TextArea("Body", Model.Body) %><br />
<%= Html.SubmitButton() %>
<% } %>
</div>
You can take it a step further and display the errors as well in the view, directly from the ModelState that you set in the controller.
<div id="content">
<%= Html.ValidationSummary() %>
<% using (Html.BeginForm()) { %>
Enter the Post Title:
<%= Html.TextBox("Title", Model.Title, 50) %>
<%= Html.ValidationMessage("Title") %><br />
Enter the Post Body:
<%= Html.TextArea("Body", Model.Body) %>
<%= Html.ValidationMessage("Body") %><br />
<%= Html.SubmitButton() %>
<% } %>
</div>
What is interesting with this approach is that you will notice I am not setting the validation summary, nor the individual validation messages in the View. I like to practice DDD concepts, which means my validation messages (and summaries) are controlled in my domain and get passed up in the form of a collection. Then, I loop throught he collection (if any errors exist) and add them to the current ModelState.AddErrors collection. The rest is automatic when you return View(post).
Lots of lots of convention is out. A few books I highly recommend that cover these patterns in much more detail are:
Professional ASP.NET MVC 1.0
Pro ASP.NET MVC 1.0 Framework
And in that order the first covers the raw nuts and bolts of the entire MVC framework. The latter covers advanced techniques outside of the Microsoft official relm, with several external tools to make your life much easier (Castle Windsor, Moq, etc).
The View is supposed to be dumb in the MVC pattern, just displaying what the Controller gives it (obviously we do often end up with some logic there but the premise is for it not to be) as a result, controls aren't responsible for their state, it'll come from the controller every time.
I can't recommend Steven Sanderson's book Pro ASP.NET MVC by Apress enough for getting to grips with this pattern and this implementation of it.
In Web Forms, control values are maintained in the viewstate so you (theoretically) don't need to reinitialize and such with each postback. The values are (again theoretically) maintained by the framework.
In ASP.NET MVC, if you follow the paradigm, you don't need to maintain state on form elements. The form element values are available on post where your controller can act on them (validation, database updates, etc.). For any form elements that are displayed once the post is processed, you (the developer) are responsible for initializing them - the framework doesn't automatically do that for you.
That said, I have read about a mechanism called TempData that allows your controller to pass data to another controller following a redirect. It is actually a session variable (or cookie if you configure it as such) but it is automatically cleaned up after the next request.
The answer really depends on the types of controls you are trying to maintain state for. For basic Html controls then it is very easy to maintain state with your Models, to do this you need to create a strongly typed view.
So if we had a User model with the properties: Username, FullName, Email, we can do the following in the view:
<%= Html.ValidationSummary() %>
<% using (Html.BeginForm()) { %>
<fieldset>
<legend>User details</legend>
<%= Html.AntiForgeryToken() %>
<p>
<label for="Username">Username:</label>
<%= Html.Textbox("Username", Model.Username, "*") %>
</p>
<p>
<label for="FullName">FullName:</label>
<%= Html.Textbox("FullName", Model.FullName, "*") %>
</p>
<p>
<label for="Email">Email:</label>
<%= Html.Textbox("Email", Model.Email, "*") %>
</p>
<p>
<input type+"submit" value="Save user" />
</p>
</fieldset>
<% } %>
We would then have two controller actions that display this view, one for get and another for post:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult User()
{
return View(new User())
}
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult User([Bind(Include = "Username,FullName,Email")]User user)
{
if (!ModelState.IsValid()) return View(user);
try
{
user.save()
// return the view again or redirect the user to another page
}
catch(Exception e)
{
ViewData["Message"] = e.Message;
return View(user)
}
}
Is this what you are looking for? Or do you want to maintain the state of Models that are not being displayed in a form between requests?
The key thing to remember is that your code executes on the server for the duration of the request and ends, the only information you can pass between your requests is basic html form data, url parameters and session information.
As other people have mentioned, I'd highly recommend Steve Sandersan's Pro ASP.NET MVC Framework for a complete understanding of working with the MVC Framework.
hidden fields, like:
<% using (Html.BeginForm<SomeController>(c=>c.SomeAction(null))) {%>
<%= Html.Hidden("SomeField", Model.SomeField)%>
<%= Html.Hidden("AnotherField", Model.AnotherField)%>
setting the specific model & not having any explicit fields (gives u hidden fields). In the example below, the Model is filled by the controller with values received from the last post, so this enables a no js option in the page that can filter based on a status:
Some Filter: <% using( Html.BeginForm<SomeController>(
c => c.SomeAction(model.SomeField, model.AnotherField, model.YetAnotherField, null, model.SomeOtherField)
)) { %>
<%= Html.DropDownList("status", Model.StatusSelectList)%>
<input type="submit" value="Filter" class="button" />
<% } %>
use extension methods to create fields, if u just want the fields to be filled with posted values when u are showing failed validation messages on the submitted form
on asp.net mvc 2 they introduced a way to save an instance in a hidden field ... encoded + (I think) signed
TempData if everything of the above doesn't do it (goes through session - cleaned on the next request)
as u mentioned, when using ajax the state is already in the previously loaded fields in the client site. If u l8r on need to do a full post, update any field u might need to with your js.
The above are all different independent options to achieve it that can be used in different scenarios. There are more options I didn't mention i.e. cookies, session, store stuff in db (like for a resumable multi step wizard), parameters passed to an action. There is no 1 single mechanism to rule them all, and there shouldn't be.
The best way to do this, i think, is to serialize your original model to a hidden field, then deserialize it and update the model on post. This is somewhat similair to the viewstate approach, only you have to implement it yourself. I use this:
first i need some methods that make things easier:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using LuvDaSun.Extensions;
using System.Web.UI;
namespace LuvDaSun.Web.Mvc
{
public static class HtmlHelperExtensions
{
static LosFormatter _losFormatter = new LosFormatter();
public static string Serialize(this HtmlHelper helper, object objectInstance)
{
var sb = new StringBuilder();
using (var writer = new System.IO.StringWriter(sb))
{
_losFormatter.Serialize(writer, objectInstance);
}
return sb.ToString();
}
}
[AttributeUsage(AttributeTargets.Parameter)]
public class DeserializeAttribute : CustomModelBinderAttribute
{
public override IModelBinder GetBinder()
{
return new DeserializeModelBinder();
}
}
public class DeserializeModelBinder : IModelBinder
{
static LosFormatter _losFormatter = new LosFormatter();
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType.IsArray)
{
var type = bindingContext.ModelType.GetElementType();
var serializedObjects = (string[])bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ConvertTo(typeof(string[]));
var deserializedObjects = Array.CreateInstance(bindingContext.ModelType.GetElementType(), serializedObjects.Length);
for (var index = 0; index < serializedObjects.Length; index++)
{
var serializedObject = serializedObjects[index];
var deserializedObject = _losFormatter.Deserialize(serializedObject);
deserializedObjects.SetValue(deserializedObject, index);
}
return deserializedObjects;
}
else
{
var serializedObject = (string)bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ConvertTo(typeof(string));
var deserializedObject = _losFormatter.Deserialize(serializedObject);
return deserializedObject;
}
}
}
}
then in my controller i have something like this (to update a product)
public ActionResult Update(string productKey)
{
var model = _shopping.RetrieveProduct(productKey);
return View(model);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Update([Deserialize]Shopping.IProduct _model, FormCollection collection)
{
UpdateModel(model);
model.Save();
return RedirectAfterPost();
}
and i need a hidden field that holds the serialized object in the form:
<%
using (Html.BeginRouteForm("Product", FormMethod.Post, new { id = UniqueID, }))
{
%>
<%= Html.Hidden("Model", Html.Serialize(Model)) %>
<h1>
Product bewerken</h1>
<p>
<label for="<%=UniqueID %>_Name">
Naam:</label>
<input id="<%=UniqueID %>_Name" name="Name" type="text" value="<%= Html.AttributeEncode(Model.Name) %>"
class="required" />
<br />
</p>
<p>
Omschrijving:<br />
<textarea id="<%= UniqueID %>_Description" name="Description" cols="40" rows="8"><%= Html.Encode(Model.Description) %></textarea>
<br />
</p>
<p>
<label for="<%=UniqueID %>_Price">
Prijs:</label>
<input id="<%= UniqueID %>_Price" name="Price" type="text" value="<%= Model.Price.ToString("0.00") %>"
class="required" />
<br />
</p>
<ul class="Commands">
<li>Annuleren</li>
<li>
<input type="submit" value="Opslaan" /></li>
</ul>
<%
}
%>
<script type="text/javascript">
jQuery('#<%= UniqueID %>').validate();
</script>
as you can see, a hidden field (Model) is added to the form. It contains the serialization information for the original object. When the form is posted, the hidden field is also posted (ofcourse) and the contents are deserialized by the custom modelbinder to the original object which is then updated and saved by the controller.
Do note that the object you are serializing needs to be decorated with the Serializable attribute or needs to have a TypeConverter that can convert the object to a string.
The LosFormatter (Limited Object Serialization) is used by the viewstate in webforms. It also offers encryptionn of the serialization data.
greets...
AJAX calls is what we do. If you're talking about grids in general, check out JQGrid and how they recommend the AJAX implementation.
Inside of an asp.net mvc partial view, I have an Ajax form that posts a value and replaces the contents of its parent container with another instance of the form.
Index.aspx view:
<div id="tags">
<% Html.RenderPartial("Tags", Model); %>
</div>
Tags.ascx partial view:
<% using(Ajax.BeginForm("tag", new AjaxOptions { UpdateTargetId = "tags" }))
{ %>
Add tag: <%= Html.TextBox("tagName")%>
<input type="submit" value="Add" />
<% } %>
The controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Tag(string tagName) {
// do stuff
return PartialView("Tags", ...);
}
The problem is when the new instance of the form returns, the posted value is already stored in the input field. As in, whatever I posted as the 'tagName' will stay in the textbox. Firebug shows that the value is hardcoded in the response.
Is there any way to clear the input textbox's value when returning the partial view?
I've tried:
<%= Html.TextBox("tagName", string.Empty)%>
and
<%= Html.TextBox("tagName", string.Empty, new { value = "" })%>`
neither of which do anything.
EDIT:
I realize there are js solutions, which I may end up having to use, but I was wondering if there were any ways of doing it in the backend?
I'm not sure if this solution is "good enough" for you, but couldn't you just empty the form in a JS callback function from your ajax call? If you're using jQuery on your site, the callback function could look something like this:
function emptyFormOnReturn() {
$(':input').val();
}
I am not entirely sure if it will, but in case the above code also removes the text on your submit button, change the selector to ':input[type!=submit]'.
yes you should use jquery to set values on response
if you change your code to use jquery for ajax operations, you can call you settingvalues function on success callback...example:
http://docs.jquery.com/Ajax/jQuery.ajax#options