c# - 将模型传递给局部 View ?

标签 c# model-view-controller asp.net-mvc-3

这是我的部分:

@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/

相关文章:

c# - 如何使用 EF 在 MVC3 中包含另一个表?将数据检索到列表中

c# - 如何在没有异常处理的情况下检查服务器是否正在监听

c# - 如何在 .net 中获取数字的大小?

Ajax http 500错误Azure不在本地

visual-studio-2010 - MVC3 安装在至少两台 PC 上不起作用

c# - .NET MVC 3 在 C# 中向 SelectListItem 添加属性

c# - Intellitest命令行调用

c# - 从控制台应用程序打开文档时可以禁用 Word 按钮吗?

java - 我可以在不同的 Action 类之间传播 struts2 ActionErrors 吗?

java - Java 和 JavaFX 中的 MVC 分离 (fxml)