Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I use inside a for-each loop:

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

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.

like image 212
Yoda Avatar asked Sep 02 '14 20:09

Yoda


3 Answers

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

However, if you're determined to use HTML attributes only, you can specify them in a dynamic object:

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

And access them within the editor using @ViewData:

<div>
     @ViewData["PersonId"]
     @ViewData["PersonName"]
     @ViewData["PersonAge"]
     etc...
</div>
like image 52
WolfgangDeveloper Avatar answered Nov 04 '22 19:11

WolfgangDeveloper


Try:

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

The outer anonymous object is what populates 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.

like image 38
Chris Pratt Avatar answered Nov 04 '22 17:11

Chris Pratt


Seems that you haven't set the ViewData. You need to set the ViewData in the controller that returns this View. Just ViewData["PersonId"] = 10

like image 2
adelb Avatar answered Nov 04 '22 17:11

adelb