Validation firing in ASP.NET MVC
Posted
by rkrauter
on Stack Overflow
See other posts from Stack Overflow
or by rkrauter
Published on 2010-03-31T22:06:23Z
Indexed on
2010/03/31
22:13 UTC
Read the original article
Hit count: 561
I am lost on this MVC project I am working on. I also read Brad Wilsons article. http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html
I have this:
public class Employee
{
[Required]
public int ID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
and these in a controller:
public ActionResult Edit(int id)
{
var emp = GetEmployee();
return View(emp);
}
[HttpPost]
public ActionResult Edit(int id, Employee empBack)
{
var emp = GetEmployee();
if (TryUpdateModel(emp,new string[] { "LastName"})) {
Response.Write("success");
}
return View(emp);
}
public Employee GetEmployee()
{
return new Employee {
FirstName = "Tom",
LastName = "Jim",
ID = 3
};
}
and my view has the following:
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary() %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.FirstName) %>
</div>
<div class="editor-field">
<%= Html.DisplayFor(model => model.FirstName) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.LastName) %>
</div>
<div class="editor-field">
<%= Html.TextBoxOrLabelFor(model => model.LastName, true)%>
<%= Html.ValidationMessageFor(model => model.LastName) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
Note that the only field editable is the LastName. When I postback, I get back the original employee and try to update it with only the LastName property. But but I see on the page is the following error:
•The FirstName field is required.
This from what I understand, is because the TryUpdateModel failed. But why? I told it to update only the LastName property.
I am using MVC2 RTM
Thanks in advance.
© Stack Overflow or respective owner