How to have a sub view in MVC?
-
06-07-2019 - |
Question
I am quite new with this MVC in ASP.NET. If I have a page which has Tournament class (in Detail mode) and underneath it has a list of PlayRoundHoles class which it's comes from stored procedure due to a complex query.
How do I achieve this to display this list under Tournament Detail View? I don't quite understand where this PlayRoundHoles sits in the Controller as well as the View?
Thanks
Solution
Create a ViewModel that contains all the required content for this page. In this case a ViewModel with a Tournament and List of PlayRoundHoles
public class MyViewModel
{
public Tournament MyTournament { get; set; }
public IList<PlayRoundHoles> MyPlayRoundHoles { get; set; }
}
Then your action method should return this strongly-viewed type.
public class TournamentController
{
public ActionResult View(int tournamentId)
{
var t = //get tournament
var p = //call sproc (may use the tournament id)
MyViewModel model = new MyViewModel();
model.MyTournament = t;
model.MyPlayRoundHoles = p;
return View(model);
}
}
Your View can then look something like
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MyViewModel>" %>
//tournament details using Model.MyTournament
//play round holes details using Model.MyPlayRoundHoles
To improve on this you could create a PartialView that seperates the display of your PlayRoundHoles
<% Html.RenderPartial("MyPlayRoundHoles", Model.MyPlayRoundHoles); %>
OTHER TIPS
You can pass instance of Tournament to View. And then render PlayRoundHoles in View.
for example see here http://stephenwalther.com/blog/archive/2009/04/13/asp.net-mvc-tip-50-ndash-create-view-models.aspx