将模型传递给局部视图?

这是我的偏见:

@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 ,现在一切都会神奇地到位。

 @using (Html.BeginForm()) { @Html.LabelFor(m => m.Title) @Html.TextBoxFor(m => m.Title) @Html.Partial("MarkdownTextArea", new MarkdownTextAreaModel { Name = "content" })  }