簡體   English   中英

將模型傳遞給局部視圖?

[英]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包含它:

@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" })

現在要說的是一個更好的解決方案是調整你的視圖模型,以便它包含對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 ,現在一切都會神奇地到位。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM