c# - 如何在没有 View 模型的情况下使用@Html.EditorFor()

标签 c# asp.net-mvc editorformodel

我想做这样的事情,这样我就可以创建一个模态对话框,我稍后会用 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")

我得到了错误

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

我不明白为什么它会关心实例在哪里或是什么(只要它的类型正确)

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

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

最佳答案

从技术上讲,问题不在于实例。它是一个表达式,而不是一个函数,您将传递到那里,EditorFor 使用的表达式解析器,用于获取它用于识别属性等的元数据,不会不支持 new 表达式。

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

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

这应该有效。

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

关于c# - 如何在没有 View 模型的情况下使用@Html.EditorFor(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10238206/

相关文章:

asp.net-mvc - 在 MVC2 中的 EditorForModel 与 DisplayForModel 模式中显示不同的字段

c# - SQL 服务器 : variable length XML storage

c# - 在云端生成唯一 ID

c# - 监 window 口中的 $ReturnValue 在 VS2015 中不起作用

asp.net-mvc - 在 vs 2010 中开箱即用运行 asp.net mvc 2 项目时出错

jquery - Ajax 调用在 Chrome 中的 URL 与 Firefox 中不同

c# - Windows 应用程序的动画

asp.net-mvc - 如何从 ActionExecutingContext 获取 MethodInfo?

asp.net-mvc-2 - 调用 EditorFor(...) 时隐藏公共(public)属性的编辑器标签?