Wednesday, April 20, 2011

ASP.NET MVC - strongly typed view with partial views (view and partial views should also have access to some global data)

Consider the following scenario:

Action Edit() is forwarded to Edit.aspx view to render the view.

Edit.aspx consists of textbox1 and two partial views (aka view user controls): part1.ascx (which has textbox2, textbox3) and part2.ascx (which has checkbox1 and checkbox2)

You want to have a strongly typed view for Edit.aspx, say, you use EditViewData class.

You also need Edit.aspx, part1.ascx and part2.ascx have access to some global information such as currentUserID, currentUserLanguage, currentUserTimezone.

Questions:

  1. How do you go about structuring the EditViewData class?
  2. How do you pass the view data to the view and partial views so that the object gets populated automatically when you submit the form and return to the Edit() http.post action?
  3. What do you pass to the Edit() http.post action?
From stackoverflow
  • Your viewdata should look like this:

    public class EditViewData
    {
        public int currentUserID { get; set; }
        public string currentUserLanguage { get; set; }
        public string currentUserTimezone { get; set; }
        // ... other stuff
    }
    

    After you strongly type your aspx, you also need to strongly type your ascxs. Then in your aspx, when you call RenderPartial, just call like usual:

    <% using (Html.BeginForm()) %>
    <% Html.RenderPartial("part1.ascx" ); %>
    <% Html.RenderPartial("part2.ascx" ); %>
    <%}%>
    

    It should automatically inherit the Model in the control. Just remember that your BeginForm should be surrounding both of your controls (ascxs).

    Michael Shimmins : +1 - All this time I've been passing this.Model as the Model parameter of partials. Didn't realise it automatically passed it down. Nice one.

0 comments:

Post a Comment