Wednesday, November 30, 2011

MVC, Single Result, and PartialViews

Let's say you have a controller that looks like this


public ActionResult Index(IPrincipal principal, int? pageNumber)
{
   return View(GetData(principle, pageNumber));
}

where the result contains
result.Vegies where these are List<{ string Label, string Value }>
result.Proteins where these are List<{ string Name, string Value }>


at the Index.cshtml, you can do this.
<table style="width800pxwidthauto ">
<tr>
<td style="width240px;">@Html.Partial("VegieView")<td>
<td style="width560px">@Html.Partial("ProteinView")<td>
<tr>
<table>
at the ../Shared/VegieView.cshtml you can do
@{ var oVegies = Model.Vegies as IEnumerable<Vegies>; }
@foreach (var x in oVegies )
{
    foreach (var y in x.Vegies)
    { 
        <div>@Html.DisplayFor(j=> y.Label)<div>
    }
}


at the ../Shared/ProteinView.cshtml you can do
@{     var oProteins = Model.Proteins as IEnumerable<Proteins>; }
@foreach (var x in oProteins)
{
    foreach (var y in x.Proteins)
    { 
        <div>@Html.DisplayFor(j=> y.Name)<div>
    }
}
So, a single controller call can update all shared view models..  
:-)  neat!
I know, you are welcome.













No comments: