views:

71

answers:

2

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.

+3  A: 

The problem is that when your form gets posted back the FirstName field is empty. The issue is that since your're passing the Employee as a parameter to your action, the validation occurs before you get a chance to make your call to GetEmployee(). You can do one of three things:

1) Remove the [Required] attribute from your FirstName field.

or

2) Add Html.HiddenFor() for this field so it will make the round-trip. Like this:

<%= Html.HiddenFor(model => model.FirstName) %>

or

3) Change your action declaration to:

public ActionResult Edit(int id, FormCollection form)

(3) is probably what you are looking for.

Keltex
That works! thanks!
rkrauter
A: 

Remember to be cautious with binding the model. This is a great post that explains why: http://www.codethinked.com/post/2009/01/08/ASPNET-MVC-Think-Before-You-Bind.aspx

brainnovative