简体   繁体   中英

MVC Display attribute from another model

so my view starts off like this

@model ApplicationName.Models.A

and takes in the my database elements from A so if i were to use @Html.DisplayFor(model => model.Whatever) it will display that element from the database in my view.

However i have another attribute that i want to also display on this same page/view. But it is in Models.B

So i need to end up with this

@Html.DisplayFor(model => model.WhateverFromB)

all help greatly appreciated

You should use a view model which encapsulates both an A and a B . For example:

class MyViewModel
{
    public ApplicationName.Models.A A {get; set;}
    public ApplicationName.Models.B B {get; set;}
}

Then pass this single view model to the controller. You would then of course access your properties like:

@Html.DisplayFor(m => m.A.Whatever)
@Html.DisplayFor(m => m.B.WhateverFromB)

Similarly if you do not need every property from A and B , or the semantic difference between the two database objects is not important to the view, you might consider doing the following instead:

class MyViewModel
{
    public object Whatever {get; set;}
    public object WhateverFromB {get; set;}
}

Populate the individual properties of the view model and use accordingly. You can of course use a combination of the two, including a full A along with a WhateverFromB .

You should use a ViewModel for this. When you require more than one model in your view this is a good way to go. Include what you need from the Models you are using in the ViewModel class and reference it in your view instead of the Model.

This will get you going with ViewModels http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-3

ViewBags and ViewData will work but there are appropriate times to use each. http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications

Realistically you should create a ViewModel which contains all the properties you need and you can populate that ViewModel from multiple Models. Then use the ViewModel as the 'model' in the MVC page.

However to answer your question. Just write an additional Html.Display entry

In your controller

ViewBag.WhateverFromB = b_obj;

and then in your view

@Html.Display(ViewBag.WhateverFromB)

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