【问题标题】:Returning an EditorTemplate as a Partial View from a Controller从控制器返回 EditorTemplate 作为局部视图
【发布时间】:2011-12-06 16:18:54
【问题描述】:

我想从我的控制器返回一个 EditorTemplate 作为部分视图。

我目前正在做:

public ActionResult Create([Bind(Prefix="Create")]CreateViewModel model)
{
    return PartialView("~/Views/Shared/EditorTemplates/Template.cshtml", model);
}

问题是,在我这样做之后,Create_ 前缀从我的视野中消失了。有没有办法将编辑器模板作为部分视图返回并保留前缀?

索引.cshtml @model 索引视图模型

@using(Html.BeginForm("Create"))
{
    @Html.EditorFor(m => m.Create, "Template")

    <input type="submit" value="Save" />
}

我通过 AJAX 调用提交此表单。当我最初调用 EditorFor 时,所有字段的前缀都是 Create_。但是,在我提交表单并返回此 PartialView 后,前缀丢失了。

【问题讨论】:

  • 你为什么不直接使用EditorFor?
  • 我最初是。我正在使用 AJAX 调用发布我的表单,当表单无效时,我需要将其作为部分视图返回并替换内容

标签: .net asp.net-mvc asp.net-mvc-3 mvc-editor-templates


【解决方案1】:

由于模板没有在主视图的上下文中调用,因此它失去了它的上下文。在这种情况下,您可以按如下方式定义前缀:

public ActionResult Create([Bind(Prefix="Create")]CreateViewModel model)
{
    ViewData.TemplateInfo.HtmlFieldPrefix = "Create";
    return PartialView("~/Views/Shared/EditorTemplates/Template.cshtml", model);
}

【讨论】:

  • 你不能在控制器中也这样做吗?
  • @SLaks,是的,你可以,这是一个绝妙的主意,而且比在模板中做的解决方案要好得多。会更新我的帖子。谢谢。
  • 哈,我正要在找到这个后自己发布答案。实际上,您也可以在控制器中执行此操作。
  • 我可能会创建一些实用方法来检查模型以查找 Bind 属性,如果找到具有前缀的模型,它会将前缀设置为该值。
  • 达林,我喜欢你的回答。每次我遇到问题时,我都可以在这里找到最佳答案,您的答案。非常感谢)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
相关资源
最近更新 更多