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

后端 未结 1 482
一整个雨季
一整个雨季 2020-12-01 19:10

I have the following types and classes:

namespace MVC.Models

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

public class EditableCon         


        
相关标签:
1条回答
  • 2020-12-01 19:47

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题