简体   繁体   English

如何在没有视图模型的情况下使用@ Html.EditorFor()

[英]How to Use @Html.EditorFor() without the view model

I want to do something like this so I can create a modal dialog that I'll invoke late with jQuery 我想做这样的事情,所以我可以创建一个模态对话框,我将用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>

On this line 在这条线上

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

I get the error 我收到了错误

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. 模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式。

I don't understand why it would care where or what the instance is (as long as its the right type) 我不明白为什么它会关心实例的位置或内容(只要它的类型正确)

@Html.Partial("~/Views/Shared/EditorTemplates/ViewModel.cshtml", new ViewModel()) does the trick, but I have to declare the full path the the template...this sucks a bit. @ Html.Partial(“〜/ Views / Shared / EditorTemplates / ViewModel.cshtml”,新的ViewModel())可以解决这个问题,但是我必须声明模板的完整路径......这很糟糕。

so is there a better way to do it? 这样有更好的方法吗?

Technically it's not the instance that's the problem. 从技术上讲,这不是问题的实例 It's an expression , not a function, that you're passing there and the expression parser used by EditorFor , to get the meta data it uses to identify the properties etc, doesn't support new expressions. 它是一个表达式 ,而不是一个函数,你要传递给它,并且EditorFor使用的表达式解析器,用于获取它用于识别属性等的元数据,不支持new表达式。

You can simply declare a new instance of the model outside of the EditorFor statement and do this: 您可以在EditorFor语句之外简单地声明模型的新实例,并执行以下操作:

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

That should work. 这应该工作。

That said - not using part of the model in the expression is a little weird. 也就是说 - 在表达式中使用model一部分有点奇怪。 You should perhaps consider extracting the dialog out to it's own partial view that has ViewModel as it's model type, and then you can use EditorForModel in that, and call it from this parent view using a new ViewModel() as the model you pass to it. 您应该考虑将对话框提取到它自己的部分视图中,该视图具有ViewModel作为模型类型,然后您可以在其中使用EditorForModel ,并使用new ViewModel()作为传递给它的模型从此父视图中调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM