MVC3 - Two models in one View - Error - How to classify
I would like to use two models in one view. For that I have the following set up. In a single .cs file I have the following model code:
public class Class1
{
//List of atttributes 1.
}
public class Class2
{
//List of atttributes 2.
}
public class ParentView
{
public Class1 Class1{get; set;}
public Class2 Class2{get; set;}
}
To make use of these two classes in one view I reference
@model IEnumerable<Project.Models.ParentView>
in the View .cshtml page. and In my view code there is this code that is breaking up .. I get an error saying - "The models.parentview开发者_如何学C does not have a definition of Class1Attribute and no extension method.....etc.." How can I classify the statement below so that it recognizes the attribute.
@foreach (var item in Model)
{
@Html.DisplayFor(modelItem => item.Class1Attribute)
@Html.DisplayFor(modelItem => item.Class1Atttribute)
}
thanks for your help.
Use
@Html.DisplayFor(modelItem => modelItem.Class1.Class1Attribute)
Alternatively you could do something like
@foreach (var item in Model.Class1)
{
@Html.DisplayFor(modelItem => item.Class1Attribute1)
@Html.DisplayFor(modelItem => item.Class1Attribute2)
}
Your properties are called Class1
and Class2
=>
@Html.DisplayFor(x => x.Class1.Class1Attribute)
@Html.DisplayFor(x => x.Class2.Class2Attribute)
or even better use display templates instead of writing any loops:
@Html.DisplayForModel()
and then inside ~/Views/Shared/DisplayTemplates/ParentView
:
@model ParentView
@Html.DisplayFor(x => x.Class1)
@Html.DisplayFor(x => x.Class2)
and inside ~/Views/Shared/DisplayTemplates/Class1.cshtml
:
@model Class1
@Html.DisplayFor(x => x.Class1Attribute)
and inside ~/Views/Shared/DisplayTemplates/Class2.cshtml
:
@model Class2
@Html.DisplayFor(x => x.Class2Attribute)
@Html.DisplayFor(modelItem => item.Class1.Class1Attribute)
Do you have multiple ParentViews in your Model? If not then you can just have
@model Project.Models.ParentView
Then reference your Class Attributes as
@Html.DisplayFor(modelItem => Model.Class1.Class1Attribute)
@Html.DisplayFor(modelItem => Model.Class2.Class2Attribute)
I think your loop should be as follows
@foreach (var item in Model)
{
@Html.DisplayFor(modelItem => item.Class1.Class1Attribute)
@Html.DisplayFor(modelItem => item.Class1.Class1Atttribute)
}
I asssumed Class1Attribute
is a property in Class1
class
精彩评论