Custom ViewModel not displaying values in TextBoxFor TextBoxFor(Model => Model.Object1.Name)
I have a custom Model, which contains another custom object (Objects1.Object2), I am correctly populating the object prior to display in the view and
<%: Model.Object1.Name 开发者_Python百科%> displays the data correctly yet <%: Html.TextBoxFor(model => model.Object1.Name) %> displays no data.
I am new to MVC and would love to get around this issue as it is a stopping point to creating custom data model.
Any info is greatly appreciated.
Are you trying to modify this in a POST action? If you are then note that HTML helpers such as TextBoxFor
will first read data from model state and after this from the model. So if your post action looks like this:
[HttpPost]
public ActionResult Index(SomeViewModel model)
{
model.Object1.Name = "some new value";
return View(model);
}
you need to remove it from model state or you will always get old value:
[HttpPost]
public ActionResult Index(SomeViewModel model)
{
ModelState.Remove("Object1.Name");
model.Object1.Name = "some new value";
return View(model);
}
If you are doing this in the GET action there shouldn't be absolutely any problems displaying the value:
public ActionResult Index()
{
var model = new SomeViewModel
{
Object1 = new TypeOfObject1
{
Name = "foo bar"
}
};
return View(model);
}
and then in the view:
<%= Html.TextBoxFor(x => x.Object1.Name) %>
should display the proper value.
精彩评论