ASP.NET MVC Html.Editor pass model to Editor Template

北城余情 提交于 2019-12-24 02:16:06

问题


I have an Editor Template called "Address.cshtml" that has a model defined as:

@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.


回答1:


The only purpose of EditorFor is to work with your view's model. 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. 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.




回答2:


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. For example:

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

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


来源:https://stackoverflow.com/questions/28347792/asp-net-mvc-html-editor-pass-model-to-editor-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!