Csharp/C#教程:与嵌套子模型和ASP.NET MVC中的PartialViews进行模型绑定分享


与嵌套子模型和ASP.NET MVC中的PartialViews进行模型绑定

我有以下类型和类:

namespace MVC.Models public class Page { public EditableContent Content {get; set; } } public class EditableContent { public TemplateSection SidebarLeft {get; set; } public TemplateSection SidebarRight {get; set; } } 

我想在Edit.aspx视图中编辑Page实例。 因为EditableContent也附加到其他模型,所以我有一个名为ContentEditor.ascxPartialView ,它是强类型的,并且接受一个EditableContent实例并呈现它。

渲染部分一切正常,但是当我发布时 – 我的ContentEditor内的所有内容都没有绑定 – 这意味着Page.Contentnull

在PartialView上,我使用强类型的Html Helpers来执行此操作:

  m.TemplateId) %> 

但是因为ContentEditor.ascx呈现的表单上的输入元素没有获得其id属性的Content前缀 – 这些值不会绑定到Page

我尝试使用松散类型的助手来克服这个问题:

  

当我处理一个属于List的属性时,它变得非常难看。 然后我必须手动渲染集合索引。

我应该将Page和EditableContent作为参数添加到控制器操作中吗?:

 public ActionResult Edit(Page page, EditableContent content) { ... } 

我错过了什么?

我建议你使用EditorFor帮助器

模型:

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

查看/首页/的Index.aspx:

 <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>  Home Page   <% 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") %>  <% } %>  

查看/共享/ EditorTemplates / EditableContent.ascx:

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <%= Html.TextBoxFor(m => m.SidebarLeft) %> 
<%= Html.TextBoxFor(m => m.SidebarRight) %>

最后是Controller / HomeController:

上述就是C#学习教程:与嵌套子模型和ASP.NET MVC中的PartialViews进行模型绑定分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 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); } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/996845.html

(0)
上一篇 2021年12月25日
下一篇 2021年12月25日

精彩推荐