这是我的偏爱:
@model RazorSharpBlog.Models.MarkdownTextAreaModel
<div class="wmd-panel">
<div id="wmd-button-bar-@Model.Name"></div>
@Html.TextAreaFor(m => m.Name, new { @id = "wmd-input-" + @Model.Name, @class = "wmd-input" })
</div>
<div class="wmd-panel-separator"></div>
<div id="wmd-preview-@Model.Name" class="wmd-panel wmd-preview"></div>
<div class="wmd-panel-separator"></div>
我试图在View
:
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.Title)
@Html.TextBoxFor(m => m.Title)
@Html.Partial("MarkdownTextArea", new { Name = "content" })
<input type="submit" value="Post" />
}
这些是模型类:
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; }
}
我做错了什么,为了使我的部分可重复使用,我应该怎么做?
答案 0 :(得分:14)
您的部分期望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)
<input type="submit" value="Post" />
}
然后为了遵循标准惯例,将你的部分移到~/Views/YourControllerName/EditorTemplates/MarkdownTextAreaModel.cshtml
,现在一切都会神奇地到位。
答案 1 :(得分:0)
@using (Html.BeginForm()) {
@Html.LabelFor(m => m.Title) @Html.TextBoxFor(m => m.Title)
@Html.Partial("MarkdownTextArea", new MarkdownTextAreaModel { Name = "content" })
<input type="submit" value="Post" />
}