简体   繁体   English

如何通过 @Html.EditorFor 通过 ViewData 将值传递给编辑器模板

[英]How to pass value by ViewData to Editor Template by @Html.EditorFor

In the view strongly typed view against @model System.Tuple<Person, List<Survey>>在针对@model System.Tuple<Person, List<Survey>>强类型视图中

I use inside a for-each loop:我在 for-each 循环中使用:

  @Html.EditorFor(x => survey.Questions)

to render questions in a `Survey.在“调查”中提出问题。 It works flawless.它完美无缺。

Now I would also like to pass additional data to the custom Editor Template.现在我还想将附加数据传递给自定义编辑器模板。 I did:我做了:

@Html.EditorFor(x => survey.Questions, new { htmlAttributes = new { PersonId = 1000 } })

and then in the Edtior Template I want to refer to this PersonId and display it.然后在 Edtior 模板中我想引用这个PersonId并显示它。

This is Editor Template I made(shortcut for question purposes):这是我制作的编辑器模板(用于提问的快捷方式):

  @using WebApplication2.Models
    @model   Question
    <div>
        @ViewData["PersonId"]
    </div>

but nothing shows up.但什么也没有出现。

How to properly pass PersonId = 1000 to this EditorTemplate.如何正确地将PersonId = 1000传递给这个 EditorTemplate。

After some searching around found the following stack-overflow answer for iterating through nested properties.经过一番搜索,找到了以下用于迭代嵌套属性的堆栈溢出答案。 I was unable to get the cast to "dynamic" working, but using reflection correctly retrieved the nested anonymous object.我无法使演员表“动态”工作,但使用反射正确检索了嵌套的匿名对象。 https://stackoverflow.com/a/13981462/1046155 https://stackoverflow.com/a/13981462/1046155

However, if you're determined to use HTML attributes only, you can specify them in a dynamic object:但是,如果您决定只使用 HTML 属性,则可以在动态对象中指定它们:

@Html.EditorFor(x => survey.Questions, new { PersonId = 1000, PersonName = "John", PersonAge=10, etc... })

And access them within the editor using @ViewData:并使用@ViewData 在编辑器中访问它们:

<div>
     @ViewData["PersonId"]
     @ViewData["PersonName"]
     @ViewData["PersonAge"]
     etc...
</div>

Try:尝试:

@ViewData["htmlAttributes"]["PersonId"]

The outer anonymous object is what populates ViewData .外部匿名对象是填充ViewData Though, if you use the above, you need to take care that you check that ViewData["htmlAttributes"] actually exists before trying to reference "PersonId" off of it.但是,如果您使用上述内容,则在尝试从中引用“PersonId”之前,您需要注意检查ViewData["htmlAttributes"]确实存在。

Seems that you haven't set the ViewData .似乎您还没有设置ViewData You need to set the ViewData in the controller that returns this View.您需要在返回此视图的控制器中设置ViewData Just ViewData["PersonId"] = 10只是ViewData["PersonId"] = 10

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

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