简体   繁体   中英

Displaying data from one model on the view of another model: did I do it right?

This question actually has two parts to it:

  1. Is what I did correct?
  2. Is a Partial View something I should be using?

I want to display records from my Event model on the Index page of the Home controller. By default, no data is sent to the Index view of the Home controller let alone does there exist a way to display. The way I solved this was to copy most of the content of Event\\Index.cshtml to Home\\Index.cshtml as well as some lines from EventController.cs to HomeController.cs.

I added lines 3 and 6 to HomeController.cs as seen below:

1  public class HomeController : Controller
2  {
3    private ETODbContext db = new ETODbContext();
4    public ActionResult Index()
5   {
6      return View(db.Events.ToList());
7      //return View();
9    }
10 ...

I question whether this is the right approach because what will I do when I also want to display data from another model in the same Home\\Index view?

As to my second question, since I've duplicated the view code of Event\\Index.cshtml into Home\\Index.cshtml I now have to maintain that code in two places. This sounds like a great time to utilize a partial view that's used in both files. Do I have the right idea here?

As for the question about the models, you should create a ViewModel which will contain the data that you want to represent (one model in the beginning and you can add more models later):

public class HomeViewModel
{
    public IList<Event> Events {get;set;}
    public IList<AnotherModel> AnotherModels {get;set;}
}

You will then use this model in your view.

Constructing this viewmodel in controller action:

public class HomeController : Controller
{
    private ETODbContext db = new ETODbContext();
    public ActionResult Index()
    {
        var model = new HomeViewModel {Events = db.Events.ToList()};
        return View(model);
    }
}

As for the second part of the question, you can extract the similar parts of thew views into a partial view which will be then rendered in both views:

_Events.cshtml (you can place it in the Shared folder, so that it will be found automatically there)

    @model IList<Event>
    <div>
        @foreach(var ev in Model)
        {
           <h2>@ev.Name</h2>
        }
   </div>

In you home index view:

@model HomeViewModel

<div>@Html.Partial("_Events", Model.Events)</div>

In you events index view:

@model IList<Event>

<div>@Html.Partial("_Events", Model)</div>

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