Reputation: 2741
trying to grasp how to pass back the following data as a model to the controller. I want to consume the model and add everything to a database afterwards. When I submit the form back to the controller, the model is empty. Is it because every thing else is null? do I have to pass everything else back as hidden fields? How do I sort that all out on the View before getting to the controller?
My controller basically deserializes an xml file that looks like this back to the view
<category>
<id>1</id>
<description>movies</description>
<genre>
<genres>
<id>1</id>
<name>comedy</name>
</genres>
<genres>
<id>2</id>
<name>action</name>
</genres>
<genres>
<id>3</id>
<name>adventure</name>
</genres>
<genres>
<id>4</id>
<name>drama</name>
</genres>
<genres>
<id>5</id>
<name>romance</name>
</genres>
</genres>
</category>
The view / form looks like this
<form>
<ul>
@for (int x = 0; x < Model.categories[i].genres.Count(); x++)
{
<li>
<label for="@Model.categories[i].genres[x].name">
<input type="checkbox" name="@Model.categories[i].genres[x].name" value="@Model.categories[i].genres[x].id" checked="@Model.categories[i].genres[x].selected" /> @Model.categories[i].genres[x].name
</label>
</li>
}
</ul>
</form>
Upvotes: 0
Views: 1329
Reputation: 39045
Give all your checkboxes a fixed name, like GenreIds.
Then, in your action you should receive a string[] genreIds
parameter.
When posting the form, the genreIds is posted as am array, so it must be received in an array parameter.
If this doesn't work because you have many categories and want to receive each group of GenreIds in its own category, then you can send a JSON representation of the form values and receive and deserialize it on the server side. To do so:
On the razor template:
Handle the form sumit event, and:
On the server side:
If you use JSON.NET you can convert the JSON to XML, or to an anonymous type object. There are another posibilities.
Remember that in any case, the genre Ids will always be string[]
(or int
, if ti's the case) and this arrays will only contain the checked values.
There is a last posibility which is processing the Request.Form
"manually". But this is harder to do.
Upvotes: 1
Reputation: 11308
Try using CheckboxFor instead of the input tag.
As for your code, you don't have an ID associated with your checkbox. How are you supposed to be receiving it back in your controller?
Upvotes: 0