2

Is it possible to dynamically add an Editor Template to my view, after a button is clicked, for example?

At the moment I'm doing this in my main view to bind a list of ObjectA objects to my model (inside a form):

@Html.EditorFor(x => x.ObjectA)

and in the Editor Template I'm binding the properties for ObjectA:

@Html.DisplayFor(x => x.ID)
@Html.CheckBoxFor(x => x.BoolA)

But if I don't want to always load this editor template, is there a way to bind it dynamically to the model, using JS?

It's because it makes an additional request to the Database which I can omit by allowing the user to choose whether or not to make the request.

Is this possible?

CCovey
  • 799
  • 1
  • 10
  • 17
sparta223
  • 293
  • 1
  • 3
  • 12

1 Answers1

2

You can't do that with EditorFor on client because the razor is transformed in html on server side.

You can do this if you make use of PartialView, where you can include your EditorFor.

You make a ajax call with js for this PartialView, but in axaj call you have to specify the id to query that object inside action.

At the end you will append the result, html content, of the call in your page.

Community
  • 1
  • 1
adricadar
  • 9,971
  • 5
  • 33
  • 46
  • So you mean having a partial view in which I have EditorFor. Do you think doing this will bind to the model, however? Am I not going to have prefix problems? – sparta223 Apr 22 '15 at 08:56
  • I tried it and it doesn't bind to the model (obviously). I decided to add an extra boolean to my model which checks whether it should make the request or not so when the user clicks a button it refreshes the page with an updated model that decides whether or not to display more data based on the user's choice – sparta223 Apr 22 '15 at 12:08
  • @sparta223 You tried to make `@Html.EditorFor(x => x.ObjectA)` or `@Html.EditorFor(x => x)` ? – adricadar Apr 22 '15 at 12:11
  • I made a partial view in which I only had @Html.EditorForModel() which was using ObjectA as the model – sparta223 Apr 22 '15 at 13:53
  • @sparta223 tis is the reason why didn't bind, you needed an *empty model* with property `ObjectA` and to use `@Html.EditorFor(x => x.ObjectA) ` – adricadar Apr 22 '15 at 13:57
  • I don't understand. Could you please include some code for the solution you are suggesting? – sparta223 Apr 22 '15 at 14:51