InsqThew
InsqThew

Reputation: 597

ASP.NET MVC3: Add element from list into a model's collection, from "Edit" view

I have a User model, which contains a collection of Devices. Users may have any number of Devices, but each Device may only have one User.

I am making a page for editing Users. When the User's Devices collection needs to be edited, the view presents a table of Devices associated with the User, with Remove links next to each, and a table of Devices not currently associated with a User, with Add links. The view is typed to a viewmodel that contains both lists.

This is all within a partial view, so that (ideally) it can update dynamically with Ajax.

Unfortunately I am quite new to ASP.NET and MVC3, and to web development in general. How should I go about writing the view to implement this?

Most of my assumptions about how to implement this are based on this tutorial. He's doing something similar, but he's just using @Html.EditorFor and adding whatever the user types in the text field into the collection, not selecting an existing object. Presumably I need to send the ID of the selected device back to the controller, so it can move the device between lists and return the updated partial view. But the view is typed to the viewmodel, and (unless I'm mistaken) I can't send arbitrary data back to the controller in a post; I can only send the viewmodel. So it would seem I need to put the selected device's ID into the viewmodel before posting it back, but if I do that then I'm violating the whole MVC pattern by manipulating data in the view.

This is a pretty rudimentary problem so I'm sure there are plenty of solutions, but unfortunately I lack enough domain knowledge to even know how to look for one.

Upvotes: 0

Views: 541

Answers (1)

diegoe
diegoe

Reputation: 256

You can send additional data to the controller (not only the viewmodel), for example, for the list of devices you can create checkboxes for each item, each checkbox must have the same name and a different value, something like this:

<input type="checkbox" name="devices" value="dev1" />
<input type="checkbox" name="devices" value="dev2" />
<input type="checkbox" name="devices" value="dev3" />

In your controller the method can receive a list of data...

public ActionResult UpdateUser(User usermodel,string[] devices){ ... }

Parameter devices contains a list of devices ids selected when the user submits the form (assuming that checkboxes are inside a form and the user submit it).

This is a way to do it, surely there are other ways.

Upvotes: 1

Related Questions