将模型传递给局部视图? [英] Pass a model to a partial view?
问题描述
这是我的部分:
@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
中:
I'm trying to include it like this in my 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; }
}
我在做什么错,我应该怎么做才能使我的部分可重用性?
What am I doing wrong, how should I do this in order to make my partial reusable?
推荐答案
您的部分希望使用MarkdownTextAreaModel
类的实例.这样做,而不是传递一个无论如何都会抛出的匿名对象:
Your partial expects an instance of the MarkdownTextAreaModel
class. So do so, instead of passing an anonymous object which would throw anyways:
@Html.Partial("MarkdownTextArea", new MarkdownTextAreaModel { Name = "content" })
现在可以说,更好的解决方案是调整视图模型,使其包含对MarkdownTextAreaModel
的引用,并在视图中使用编辑器模板而不是局部视图,就像这样:
Now this being said a far better solution would be to adapt your view model, so that it contains a reference to MarkdownTextAreaModel
and use editor templates instead of partials in your views, just like so:
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
:
then of course readapt the controller serving this view so that it populates the MarkDown
of your view model:
public ActionResult Foo()
{
BlogContentModel model = .... fetch this model from somewhere (a repository?)
model.MarkDown = new MarkdownTextAreaModel
{
Name = "contect"
};
return View(model);
}
然后在您的主视图内简单地:
and then inside your main view simply:
@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
,现在一切都会按部就班地神奇地出现.
and then in order to follow standard conventions move your partial to ~/Views/YourControllerName/EditorTemplates/MarkdownTextAreaModel.cshtml
and now everything will magically come into place as it should.
这篇关于将模型传递给局部视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!