简体   繁体   English

ASP.NET MVC Html.Editor将模型传递给编辑器模板

[英]ASP.NET MVC Html.Editor pass model to Editor Template

I have an Editor Template called "Address.cshtml" that has a model defined as: 我有一个名为“ Address.cshtml”的编辑器模板,其模型定义为:

@model Acme.Models.Address

In a View I want call the Editor Template and pass a local variable of the same type, and define the name it will use for the variables, I've tried a number of things including: 在视图中,我想调用编辑器模板并传递相同类型的局部变量,并定义将用于变量的名称,我尝试了许多方法,包括:

@Html.Editor("address", "Address", new { Model = address })

How do I pass the model? 如何通过模型?

Note, I cannot use @Html.EditorFor() because the view uses a different model. 注意,我不能使用@ Html.EditorFor(),因为视图使用了不同的模型。

The only purpose of EditorFor is to work with your view's model. EditorFor唯一目的是使用视图的模型。 If you need to work with a completely different class instance that's not your view's model or accessible through you're view's model. 如果您需要使用不是您的视图模型或无法通过您的视图模型访问的完全不同的类实例。 Then just use Html.Partial . 然后只需使用Html.Partial They're functionally the same. 它们在功能上是相同的。 If you're worried about using a specific editor template, you can always pass the full path to the view to Html.Partial . 如果您担心使用特定的编辑器模板,则始终可以将视图的完整路径传递给Html.Partial

In a view (in its header or somewhere else, but before the row you are calling your Html.Editor) you can add the model in the ViewData with the key equals to your Html.Editor's expression and it will be used as a model in your called editor. 在视图中(在其标题或其他位置,但在调用Html.Editor的行之前),您可以在视图数据中添加模型,其键等于您的Html.Editor的表达式,它将在其中用作模型。您的编辑。 For example: 例如:

@{
    var address = new Acme.Models.Address();
    ViewData["address] = address;
}

@Html.Editor("address", "Address")

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

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