Custom ViewModel not displaying values in TextBoxFor TextBoxFor(Model => Model.Object1.Name)

前提是你 提交于 2019-12-10 10:44:40

问题


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 %> 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.


回答1:


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.



来源:https://stackoverflow.com/questions/5614615/custom-viewmodel-not-displaying-values-in-textboxfor-textboxformodel-model-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!