Thursday, August 15, 2013

MVC Pass Different Model to Partial View

Did a quick search and couldn't find this information anywhere online, so here goes.

Here's my scenario.

I Create new MVC project. (I'm using v4, but it would apply in earlier as well), and choose Internet Application. AccountModels.cs is created in my models folder.

There are 2 classes I'm concerned about. UserProfile and RegisterModel.

My scenario involves saving reuse and creating a partialview for creating and editing the user information. A fairly common scenario in web development. So I create the partialview, and use the Model Declaration of UserProfile. I include all information inside of this that will be reused among the 2 views. In my situation, the password and confirm password are the fields I'm not re-using, so those won't be included in my partialview.

So my views look like:

_UserInfo (Partial View):

@model UserProfile

    @Html.LabelFor(m => m.UserName)
    @Html.TextBoxFor(m => m.UserName)


RegisterPage:

...
Registration Form
       


               @Html.Partial("_UserInfo", Model)

                    @Html.LabelFor(m => m.Password)
                    @Html.PasswordFor(m => m.Password)
               
    ...

    But wait!  This generates an error msg stating that the model type is not the same.  How do I pass a valid model type in so that my controller can still read the data back?

    At the top of the RegistePage, I add the following:

    @model RegisterModel
    @{
        ViewBag.Title = "Register";
        UserProfile user = new UserProfile();
    }

    and change my RegisterPage to pass in user instead of Model, such as:

    @Html.Partial("_UserInfo", user)

    That's it!  Now I can reuse this in an edit profile page and simply use UserProfile as my model type, and pass it into the partialview like:

    @Html.Partial("_UserInfo", Model)

    and the partialview will render it with no problems.



    0 comments: