Setting Properties using Asp.Net MVC
This was a nifty way to set properties in previous MVC drops. I’ll demonstrate one way to migrate this to the new way of MVC.
<%= Html.RenderUserControl( "~/Views/Components/Pdf/ReportHeader.ascx", ViewData.Model.PrimaryCompany, new { PageNumber = 1, TotalPages = 7 } )%>
First you’ll need to accept ViewData items in your control. The path of least resistance is to set your existing properties using new view data items. This is done inside your user control.
public partial class ReportHeader : System.Web.Mvc.ViewUserControl<Models.Ticker.TickerViewData>
{
public int PageNumber { get; set; }
public int TotalPages { get; set; }
public string TickerUrl { get; set; }
public ReportHeader()
{
this.PageNumber = 1;
this.TotalPages = 5;
}
protected void Page_Load( object sender, EventArgs e )
{
if( ViewData["pageNumber"] != null ) this.PageNumber = (int)ViewData["pageNumber"];
if( ViewData["totalPages"] != null ) this.TotalPages = (int)ViewData["totalPages"];
this.TickerUrl = new gah.Web.Mvc.Helpers.NavigationHelper().GetTickerUrl( ViewData.Model.StockTicker );
}
}
Modify your calling view page. Notice, no <%=
<%
ViewDataDictionary pagingDictionary = new ViewDataDictionary();
pagingDictionary.Add( "pageNumber", 1 );
pagingDictionary.Add( "totalPages", 7 );
Html.RenderPartial( "~/Views/Components/Pdf/ReportHeader.ascx", pagingDictionary );
%>
I was a fan of the old style but this works just as well. Perhaps someone will write the extension that brings back anonymous property mapping…
November 27th, 2008 at 12:49 am
[…] Rusty Zarse blogged about a useful ViewData helper class, which allows you to set properties by passing values to the partial through the ViewData. […]