将模型传递给局部视图?
这是我的偏见:
@model RazorSharpBlog.Models.MarkdownTextAreaModel @Html.TextAreaFor(m => m.Name, new { @id = "wmd-input-" + @Model.Name, @class = "wmd-input" })
我试图在我的View
包含它:
@using (Html.BeginForm()) { @Html.LabelFor(m => m.Title) @Html.TextBoxFor(m => m.Title) @Html.Partial("MarkdownTextArea", new { Name = "content" }) }
这些是模型类:
public class MarkdownTextAreaModel { [Required] public string Name { get; set; } } public class BlogContentModel { [Required] [Display(Name = "Post Title")] public string Title { get; set; } [Required] [DataType(DataType.MultilineText)] [Display(Name = "Post Content")] public string Content { get; set; } }
我做错了什么,为了使我的部分可重复使用,我应该怎么做?
您的部分期望MarkdownTextAreaModel
类的实例。 所以这样做,而不是传递一个无论如何都会抛出的匿名对象:
@Html.Partial("MarkdownTextArea", new MarkdownTextAreaModel { Name = "content" })
现在要说的是一个更好的解决方案是调整你的视图模型,以便它包含对MarkdownTextAreaModel
的引用,并在你的视图中使用编辑器模板而不是部分,就像这样:
public class BlogContentModel { [Required] [Display(Name = "Post Title")] public string Title { get; set; } [Required] [DataType(DataType.MultilineText)] [Display(Name = "Post Content")] public string Content { get; set; } public MarkdownTextAreaModel MarkDown { get; set; } }
然后当然重新接受服务于此视图的控制器,以便填充视图模型的MarkDown
:
public ActionResult Foo() { BlogContentModel model = .... fetch this model from somewhere (a repository?) model.MarkDown = new MarkdownTextAreaModel { Name = "contect" }; return View(model); }
然后在主视图中简单地:
@using (Html.BeginForm()) { @Html.LabelFor(m => m.Title) @Html.TextBoxFor(m => m.Title) @Html.EditorFor(x => x.MarkDown) }
然后为了遵循标准约定,将你的部分移动到~/Views/YourControllerName/EditorTemplates/MarkdownTextAreaModel.cshtml
,现在一切都会神奇地到位。
上述就是C#学习教程:将模型传递给局部视图?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)
@using (Html.BeginForm()) { @Html.LabelFor(m => m.Title) @Html.TextBoxFor(m => m.Title) @Html.Partial("MarkdownTextArea", new MarkdownTextAreaModel { Name = "content" }) }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。
如若转载,请注明出处:https://www.ctvol.com/cdevelopment/1003593.html