【问题标题】:ASP.NET MVC EditorTemplate not being used未使用 ASP.NET MVC EditorTemplate
【发布时间】:2015-06-22 11:59:45
【问题描述】:

我目前正在 ASP.NET MVC 中创建一个网站,我想使用 EditorTemplates 在我的 ViewModel 中显示一个列表。 RowViewModel 有一个 RowDataViewModel 列表。我正在尝试为 RowViewModel 创建一个视图,我可以在其中使用

@Html.EditorFor(model => model.RowData)

因此我需要一个 EditorTemplate。我在下面创建了EditorTemplate:

Views/Shared/EditorTemplates/RowDataViewModel.cshtml

我还尝试将 EditorTemplates 文件夹放在 /Home/ 视图文件夹下,但似乎没有任何效果。在编辑器模板中没有遇到断点。我想我以前这样做过,但我可能会忘记一些事情。

有什么想法吗?

RowViewModel:

public class RowViewModel
{
    [Required]
    [Display(Name="Name")]
    public string Name { get; set; }

    public List<RowDataViewModel> RowData { get; set; }
}

RowDataViewModel:

public class RowDataViewModel
{
    public string Name { get; set; }
    public string Value { get; set; }
    public string DataType { get; set; }
}

EditorTemplate - RowDataViewModel.cshtml:

@using iDealWebRole.ViewModels
@model RowDataViewModel

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Value, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Value, "", new { @class = "text-danger" })
    </div>
</div>

【问题讨论】:

  • 你的意思是@Html.EditorFor(model =&gt; model.RowData)(不是@model.EditorFor(...))?
  • 只是我帖子中的一个错字。现在更正了:)
  • 您在此处显示的代码很好,并且可以正常工作。肯定有其他问题。
  • 我是这么想的,对吧?我真的找不到代码的任何问题。难道我无法为视图模型制作和编辑器模板吗?
  • 你确定属性RowData确实包含一些要渲染的项目吗?

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

问题出在这里:@Html.EditorFor(model =&gt; model.RowData)

您应该对 RowData 中的每一行使用您的编辑器,例如:

@for (int i = 0; i < Model.RowData.Count(); i++)
{
    @Html.EditorFor(model => Model.RowData[i])
}

【讨论】:

  • 这将生成重复的id(无效的html)和重复的name属性,这些属性不会在回发时绑定到集合。
  • Stephen Muecke 评论的编辑答案。
猜你喜欢
  • 2011-01-19
  • 1970-01-01
  • 2021-06-13
  • 2011-02-13
  • 1970-01-01
  • 2021-06-04
  • 2011-06-26
  • 2012-04-10
  • 2016-03-28
相关资源
最近更新 更多