Can i call a “shared” editor template from within a “areas” editor template, for the same model?

瘦欲@ 提交于 2020-01-13 08:31:27

问题


I've got an editor template location in:

Areas/Posts/Views/Shared/EditorTemplates/Question.cshtml

I also have one in:

/Views/Shared/EditorTemplates/Question.cshtml

For both, the model is the same.

What i'm trying to do is within a View in the Posts area, call my editor template in the area, set some HTML and then bubble back up to the main shared editor template.

Here's the Posts EditorTemplate:

@model xxx.ViewModels.QuestionViewModel
@Html.Hidden("Id", (byte)Model.QuestionType)
@Html.EditorForModel()

But all it does it render out the hidden field, not the contents of the shared editor template.

If i get rid of the Posts editor template, the shared one is rendered properly.

I'm guessing MVC/Razor thinks this is recursive or something? Like im calling the same template?

Is there any way i can tell it to go to the shared one?

Essentially, i'm trying to re-use the HTML in the shared template, but inject some sneaky HTML of my own.


回答1:


You can only have 1 template used at runtime for a given type. ASP.NET MVC first looks in areas shared templates folder and since it finds a corresponding template there it picks it up and it uses it. It then stops looking and the template you put in the main shared folder is never used. It's by design.

Is there any way i can tell it to go to the shared one?

Yes, you can explicitly specify the location of the template, but then it won't use the template in your areas folder:

@Html.EditorFor(x => x.Question, "~/Views/Shared/EditorTemplates/Question.cshtml")



回答2:


As the HTML markup for the shared editor template was very simple (just rendered a checkbox and a label), i abstracted the markup into a custom HTML helper, then called this from both the shared template and my areas template.

~/Areas/Posts/Views/Shared/EditorTemplates/Question.cshtml:

@model xxx.ViewModels.QuestionViewModel
@Html.Hidden("Id", (byte)Model.QuestionType)
@Html.QuestionCheckBoxForModel()
@Html.QuestionLabelForModel()

~/Views/Shared/EditorTemplates/Question.cshtml:

@model xxx.ViewModels.QuestionViewModel
@Html.QuestionCheckBoxForModel()
@Html.QuestionLabelForModel()


来源:https://stackoverflow.com/questions/8163003/can-i-call-a-shared-editor-template-from-within-a-areas-editor-template-for

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