简体   繁体   中英

ASP.NET MVC 1.0 nested models with partial views

I'm trying to get a nested model to bind correctly with a nested view but am not having any luck.

Here is a detailed look

This is the class

public class Foo
{ 
    public AnotherClass AnotherClass { get; set; }
    public string Name { get; set; }
    public ......
}

Inside AnotherClass we have more sub objects such as

public class AnotherClass 
{
    public AThirdClass { get; set; }
}

The third class has the properties that we want to bind to.

public class AThirdClass
{
    public string ImportantString { get; set; }
    public string SecondString { get; set; }
}

The primary view is expecting a class of type Foo. Inside of that View we call the html helper to render the partial view which expects a model of type AnotherClass which we pass in. The call would be

<% Html.RenderPartial("MyPartialView", Model.AnotherClass); %>

Inside the partial view MyPartialView we have text boxes for editing fields in AThirdClass and they are set up like this

<%= Html.TextBox("AThirdClass.ImportantString", Model.AThirdClass.ImportantString) %>

When we post back to the server I'm loosing all the data that was entered in the text box. Is this not supported in MVC 1.0? I am able to use this technique if I don't have any partial views while still using nested objects?

It looks like in MVC 2.0 you can use the EditorFor HTML helper to do what I need to do however I'm stuck on MVC 1.0.

What am I doing wrong?

I've got a work around for this.

If you pass the full view model into the partial and then reference the sub objects right from the top model then you will be fine.

I would still like to hear how anyone else has done this though.

I'm on MVC 3, still have this same issue, switched to less than ideal inheritance. If anyone knows a better way please post it.

I solved it using below code. The issue is, the Ids generated for the Partial View Templates does not comply with the MVC Model Binding rules. So try to use a variation of Partial view as shown below.

<% Html.RenderPartial("MyPartialView", Model.AnotherClass, new ViewDataDictionary(){
    TemplateInfo = new TemplateInfo() {
        HtmlFieldPrefix = "AnotherClass"
    }
}); %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM