Model binding with nested child models and PartialViews in ASP.NET MVC

I would suggest you to use the EditorFor helper

Model:

public class EditableContent
{
    public string SidebarLeft { get; set; }
    public string SidebarRight { get; set; }
}

public class Page
{
    public EditableContent Content { get; set; }
}

Views/Home/Index.aspx:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ToDD.Models.Page>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
    <%-- 
    This is the important part: It will look for 
    Views/Shared/EditorTemplates/EditableContent.ascx
    and render it. You could also specify a prefix
    --%>
    <%= Html.EditorFor(page => page.Content, "Content") %>
    <input type="submit" value="create" />
<% } %>
</asp:Content>

Views/Shared/EditorTemplates/EditableContent.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ToDD.Models.EditableContent>" %>

<%= Html.TextBoxFor(m => m.SidebarLeft) %>
<br/>
<%= Html.TextBoxFor(m => m.SidebarRight) %>

And finally Controller/HomeController:

public class HomeController : Controller
{
    public ActionResult Edit()
    {
        var page = new Page
        {
            Content = new EditableContent
            {
                SidebarLeft = "left",
                SidebarRight = "right"
            }
        };
        return View(page);
    }

    [HttpPost]
    public ActionResult Edit(Page page)
    {
        return View(page);
    }
}

Leave a Comment