I have a problem with ASP.NET MVC html helpers like TextBoxFor (), HiddenFor (), etc. If I have a model such as Employee with the name of a string member and executing Html.TextBoxFor (p => p.Name), is it wrong for me to assume that ASP.NET MVC will always use the value in the employee name? Because it is not. ASP.NET will override this binding and use what is in POST.
For exmaple, let's say I have the following code:
Model
namespace MvcApplication2.Models { public class Company { public string Name { set; get; } public List<Employee> Employees { set; get; } } public class Employee { public string Name { set; get; } } }
controller
namespace MvcApplication2.Controllers { public class HomeController : Controller { public ActionResult Company(string Name) { return View(new Company { Name = Name, Employees = new List<Employee> { new Employee { Name = "Ralph" }, new Employee { Name = "Joe" } } }); } } }
Home /Company.cshtml
@using MvcApplication2.Models; @model Company <h2>Company Name: @Model.Name</h2> @foreach (Employee emp in Model.Employees) { Html.RenderPartial("Employee", emp); }
Home /Employee.cshtml
@model MvcApplication2.Models.Employee <b>Employee Name: </b> @Html.TextBoxFor(p => p.Name);
When I hit the relative URL "Home / Company? Name = MSFT", I expected Employee.cshtml to display "Ralph" and "Joe" in the text boxes, but instead display the MSFT for both text fields. What do I need to do so that "Ralph" and "Joe" appear in text boxes? Do I have to make sure that my POST and GET variables never conflict in all layers of my view models (in this case, company and employee classes)? That seems stupid. There should be an easy workaround, right?
Here is a screenshot of the result: 
source share