How to select and pass data from the view
I'm starting to develop in ASP.NET and I can't find any example of a very simple use-case: I've got some model objects displayed on a view. I added a checkbox so that the user can choose the one he/she wants to see. Then the user clicks on a link and he/she should see the model objects he/she selected displayed in another view.
1) What's the best way to get the selected items list?
At the moment I decorated my model with an IsSelected
property because that's what I'd do in a ViewModel but that may not be the right answer.
2) How to pass the selected data to the next controller? In all the examples that I've seen, data is "hardcoded" in the link and is per-object. I haven't seen any example of a user-selection in any sample from the ASP MVC site.
EDIT: I'm afraid it wasn't that clear. What I've got is that:
<table style="width: 100%;">
<% foreach (Vehicle vehicle in Model)
{ %>
<tr>
<td>
<% 'Here be bound checkbox' %>
</td>
<td>
<%= Html.ActionLink("Show", "Index", "Map", vehicle.Name, null) %>
</td>
<td >
<%= Html.Encode(vehicle.Name) %>
</td>
<td >
<%= Html.Encode(vehicle.LastPositionReceived) %>
</td>
<td >
<%= Html.Encode(vehicle.Status) %>
</td>
<td >
<%= Html.Encode(vehicle.LocationDescription) %>
</td>
</tr>
<% } %>
</table>
By clicking on the Show
link, I can already show a SINGLE item details.
Now I'd like to have the checkbox bound to a property of my model so that I can then trigger an action (with a link or a button) so that only the SELECTED items are sent to the controller. This is the part that I haven't seen any examples about.
I could add
<% TempData.Add("Vehicles", Model); %>
somewhere and then th开发者_如何学编程e vehicles would be passed to the controller but I still need a way to bind the IsSelected
property to the model (I don't want to hook up the Checked
event and do it manually).
I hope that makes things a bit clearer.
(Thanks for the quick reply BTW ;) )
Honestly, you are not giving much information for us to give a proper answer. But here is a simple example of how you could accomplish what I think you described.
Suppose this is the part in your view where you are listing the selections to the user :
<%foreach (YourModel m in (List<YourModel>)ViewData["ModelsToList"]) {%>
<p>
<input name="selection" type="radio" value="<%=m.ID%>" id="model-<%=m.ID%>" />
<label for="model-<%=m.ID%>"><%=m.Name%></label>
</p>
<%}%>
Then you post that form to a controller action like this :
public ActionResult ShowSelectedModel(int selection) {
YourModel selectedModel = yourModelRepository.getModel(selection);
return View(selectedModel);
}
Then in your ShowSelectedModel
view you can display the user's selection.
Was that what you had in mind?
精彩评论