【问题标题】:How to Use @Html.EditorFor() without the view model如何在没有视图模型的情况下使用 @Html.EditorFor()
【发布时间】:2012-04-19 23:19:30
【问题描述】:

我想做这样的事情,这样我就可以创建一个模式对话框,稍后我会用 jQuery 调用它

<div class="modal" id="modalName" style="display: none;">
<div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Edit Contacts</h3>
</div>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new Dictionary<string, object> { { "class", "form-horizontal" } }))
{
    <div class="modal-body">
    @Html.EditorFor(model => new ViewModel(), "ViewModelTemplateName")
    </div>
    <div class="modal-footer">
        <a href="#" class="btn" data-dismiss="modal">Close</a>
        <button type="submit" class="btn btn-primary">
            Submit</button>

    </div>
}
</div>

在这条线上

@Html.EditorFor(model => new ViewModel(), "ViewModelTemplateName")

我得到了错误

模板只能用于字段访问、属性访问、 一维数组索引,或单参数自定义索引器 表达式。

我不明白为什么它会关心实例的位置或内容(只要它的类型正确)

@Html.Partial("~/Views/Shared/EditorTemplates/ViewModel.cshtml", new ViewModel()) 可以解决问题,但我必须声明模板的完整路径......这有点糟糕。

那么有没有更好的方法呢?

【问题讨论】:

  • 抱歉打错字了(为了保护无辜者)我会编辑和修正。
  • 是的,但使用模型并不总是您想要做的。数据注释很好,它们给了我们很好的验证和漂亮的名字。当我想在 jQuery 中用我的页面做一些更丰富的事情时,只需将视图模型呈现为模板就很好,它们让诸如 knockoutjs 和 twitter-bootstrap 之类的东西发挥它的魔力。

标签: c# asp.net-mvc editorformodel


【解决方案1】:

从技术上讲,问题不在于 instance。这是一个表达式,而不是一个函数,你传递到那里,EditorFor 使用的表达式解析器,用于获取它用来识别属性等的元数据,不支持@987654322 @ 表达式。

您可以简单地在 EditorFor 语句之外声明模型的新实例并执行以下操作:

@{ var emptyViewModel = new ViewModel(); }
@Html.EditorFor(model => emptyViewModel, "ViewModelTemplateName") 

应该可以的。

也就是说 - not 在表达式中使用 model 的一部分有点奇怪。您也许应该考虑将对话框提取到它自己的部分视图中,该部分视图具有 ViewModel 作为模型类型,然后您可以在其中使用 EditorForModel,并使用 new ViewModel() 作为模型从该父视图调用它传递给它。

【讨论】:

  • 是的,这行得通,谢谢......而且你对制作部分视图是正确的。我现在正在考虑实现这一点。
猜你喜欢
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
相关资源
最近更新 更多