这是我的部分:
@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; }
}
我做错了什么,我应该怎么做才能使我的部分可重用?
最佳答案
您的部分需要 MarkdownTextAreaModel
类的实例。所以这样做,而不是传递一个无论如何都会抛出的匿名对象:
@Html.Partial("MarkdownTextArea", new MarkdownTextAreaModel { Name = "content" })
现在据说更好的解决方案是调整您的 View 模型,以便它包含对 MarkdownTextAreaModel
的引用,并在您的 View 中使用编辑器模板而不是部分模板,就像这样:
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; }
}
当然,然后重新调整为该 View 提供服务的 Controller ,以便它填充 View 模型的 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
,现在一切都会神奇地按原样出现。
关于c# - 将模型传递给局部 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7393616/