tags:

views:

426

answers:

2

Hey all, this is a newbie ASP.NET MVC question.

I have a view that has a list of checkboxes and a submit button. On submit it posts to a controller method but I can't figure out how to get the values of the checkboxes. Also, I can't figure out how to get model data that I passed into the view when I'm in the post method, I tried using Html.Hidden but that didn't seem to work.

Here's the code: http://pastebin.com/m2efe8a94 (View) http://pastebin.com/m39ebc6b9 (Controller)

Thanks for any input received, Justin

+1  A: 

First thing I noticed is that your hidden fields need to be inside your form. Currently in your view, they are above the BeginForm, so they won't be included in the form submission.

To get the values of the selected check boxes, add an IsOffered parameter to your OfferTrade Action method.

public ActionResult OfferTrade(FormCollection result, List<string> IsOffered)

That parameter will contain a list of the ItemId's for all the checked IsOffered boxes.

The HtmlHelper's CheckBox works differently and I don't like the way it works, so I don't use it.

Making the IsOffered parameter type List<int> should also work if your ItemId field is an integer.

Dennis Palmer
Thanks, this fixed it!
Justin
A: 

First of all your ItemId and UserId is outside your form:

<%= Html.Hidden("ItemId", Model.ItemIWant.ItemId) %>
<%= Html.Hidden("UserId", Model.ItemIWant.UserId) %>

//...

<% using (Html.BeginForm()) {%>

Secondly you could try to make your Controller action method use "model binding" (if this is also called model binding)

public ActionResult OfferTrade(int ItemId, int UserId, IList<string> IsOfferred)

Edit Just noticed you are not using the HtmlHelper CheckBox so your list will contain only selected items, but a point still:

You might want to look into Phil Haacks post on Model Binding To A List, but there is a small change to this in the RTM version of MVC:

You dont need the ".Index" hidden fields, but then the indexes in the Name fields must be zero-indexed and increasing (by 1).

veggerby