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

In a strongly typed view with @model System.Tuple<Person, List<Survey>>

I use inside each loop:

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

to pose questions in the "Review". It works flawlessly.

Now, I would also like to pass additional data into a custom template template. I did:

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

and then in the Edtior Template I want to access this PersonId and display it.

This is the editor template I created (shortcut for questions):

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

but nothing is displayed.

How to pass PersonId = 1000 to this EditorTemplate correctly.

+6
source share
3 answers

After some searching around, the following answer was found for iterating through nested properties. I was not able to get the casting to work with "dynamic" ones, but with the help of reflection I entered the anonymous object correctly. fooobar.com/questions/442152 / ...

However, if you intend to pass only HTML attributes, you can simply specify them as a sequence:

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

And access them in the editor through:

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

Try:

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

An external anonymous object is what fills the ViewData . Although, if you use the above, you need to make sure that you really verify that ViewData["htmlAttributes"] exists before trying to reference the "PersonId".

+2
source

It seems you did not install ViewData . You need to install ViewData in the controller that returns this view. Just ViewData["PersonId"] = 10

+2
source

Source: https://habr.com/ru/post/974712/


All Articles