Question

I am writing a Razor view in ASP.NET MVC4.

I have a list of objects that I will display. I am currently using @Html.EditorFor() with an EditTemplate defined for the list of data models.

First, I would like to conditionally show / hide controls in the edit template using jquery, but I'm not sure where the script should live (in the edit template perhaps?) and how it can select only related controls in the current iteration of the edit template.

Next I would like to have an add button that generates a new instance of the controls (probably through AJAX?) and adds it to the list on the client side.

Has anybody done anything like this before? Is there a way to get the iteration count inside the template so I can put it in the class of the controls or something? I need to be able to select them in jquery so I can toggle control states.


Code looks something like this:

In main view:

@Html.EditorFor(vm => vm.ListOfChildViewModels)
<button type="button" class="btn" id="btnAddViewModel">Add view model</button>

EditorTemplate:

@MyNamespace.Web.ViewModels.VMType

@Html.DropDownListFor(vm => vm.SelectorProperty, Model.SelectorOptions)

// This checkbox should only get displayed if the dropdown has selectedIndex == 0
@Html.CheckBoxFor(vm => vm.Option1)

// This checkbox should only get displayed if the dropdown has selectedIndex == 1
@Html.CheckBoxFor(vm => vm.Option2)

// Etc...
Was it helpful?

Solution

Ended up doing the processing server-side to keep the heavy lifting there. The IDs are automatically generated through the EditTemplate the first time. Whenever I need to add / remove from the list, I pass the serialized form to the server in an AJAX call. The server then makes the request change and passes back rendered HTML of the list which can be swapped in and out client-side using jquery.

Could have used client-side binding to solve this problem, but C# on the server is more testable and compile safe at the moment. Unfortunately, the cost is round trips to the server and back to update the list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top