Tuesday, June 26, 2012

Html.RenderPartial in Razor

This example will show a Partial View. It uses two C# objects. This is one:

using System.Collections.Generic;
namespace RenderPartialExample.Core
{
   public class Customer
   {
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string PhoneNumber { get; set; }
      public string EmailAddress { get; set; }
      public List<Address> Addresses { get; set; }
   }
}

 
 

This is the other object:

using System;
namespace RenderPartialExample.Core
{
   public class Address
   {
      public Guid Id { get; set; }
      public string Street { get; set; }
      public string Suite { get; set; }
      public string City { get; set; }
      public string State { get; set; }
      public string ZipCode { get; set; }
      public bool IsBilling { get; set; }
   }
}

 
 

This is my view which repeats a partial in a foreach loop:

@using RenderPartialExample.Core
@model RenderPartialExample.Core.Customer
@{
   ViewBag.Title = "Update";
}
<h2>Update @Model.FirstName @Model.LastName</h2>
@using (Html.BeginForm("Index", "Customer"))
{
   <div>@Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName)
         </div>
   <div>@Html.LabelFor(m => m.LastName) @Html.TextBoxFor(m => m.LastName)</div>
   <div>@Html.LabelFor(m => m.PhoneNumber) @Html.TextBoxFor(m =>
         m.PhoneNumber)</div>
   <div>@Html.LabelFor(m => m.EmailAddress) @Html.TextBoxFor(m =>
         m.EmailAddress)</div>
   <table style="border: 2px solid #000000;">
      <tr><th>delete</th><th>primary</th><th></th></tr>
      @foreach(Address address in @Model.Addresses)
      {
         Html.RenderPartial("Address", new Tuple<bool, bool, Address>(false,
               address.IsBilling, address));
      }
   </table>
   <input type="submit" value="submit" />
}

 
 

This is my partial:

@model Tuple<bool,bool,RenderPartialExample.Core.Address>
<tr>
   <td>@Html.CheckBoxFor(m => m.Item1)</td>
   <td><input type="radio" name="primary" value="@Model.Item3.Id" @{
                                          if (Model.Item2)
                                          {
                                             <text>checked</text>
                                          }
                                       }/></td>
   <td nowrap>
      @Model.Item3.Street<br />
      @Model.Item3.Suite<br />
      @Model.Item3.City<br />
      @Model.Item3.State<br />
      @Model.Item3.ZipCode<br />
      @Html.ActionLink("edit me", "Update", "Address", new { Id = Model.Item3.Id }, null)
   </td>
</tr>

 
 

The end result looks like:

some MVC tinkering on Twitpic

No comments:

Post a Comment