Reputation: 2803
I have a table in my view (See picture below) where I need to collect the values from a radio button group. So then I push the next button I have a list with the values for each table row. This is my code in the view.
@foreach (var item in ViewBag.convertedSubjectsList)
{
<tr>
<td>
<br />
<br />
@item.Part
<br />
<br />
</td>
<td>
@item.Name
</td>
<td>
<form>
<input type="radio" name="used" value="yes" />
@Resources.Resources.SubjectRadioYes<br />
<input type="radio" name="used" value="no" />
@Resources.Resources.SubjectRadioNo
</form>
</td>
</tr>
}
Is this posible?
Upvotes: 0
Views: 3000
Reputation: 2428
View:
<form method=post action="@Url.Action("Save")">
<table>
@foreach (var item in ViewBag.convertedSubjectsList)
{
<tr>
<td>
<br /><br />
@item.Part
<br /><br />
</td>
<td>
@item.Name
</td>
<td>
<input type="radio" name="@item.Part" value="yes" />
Yes<br />
<input type="radio" name="@item.Part" value="no" />
No
</td>
</tr>
}
</table>
<input type="submit" value="Submit" />
</form>
Controller:
public ActionResult Save(FormCollection form)
{
foreach (var item in form.AllKeys)
{
string value = form[item];
// save data
}
}
Upvotes: 1
Reputation: 60493
Different things
All your radiobuttons should be in the same form
@using (Html.BeginForm()) {
//yourcode
}
Then I would put the "convertedSubjectList" as the model (or a part of a ViewModel used as model).
let's say the model is of type IEnumerable<ConvertedSubject>
;
then to loop and retrieve elements
@for (int i = 0; i < Model.Count; i++) {
<tr>
<td>@Html.DisplayFor(m => Model[i].Part)</td>
<td>@Html.Displayfor(m => Model[i].Name)</td>
<td>@Html.RadioButtonYesNoFor(m => Model[i].xxx)</td>//name of the property used for radio value
//you could use a CheckBoxFor, if you have only "yes/no", but as you want
</tr>
}
a little HtmlHelper
public static IHtmlString RadioButtonYesNoFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var stringBuilder = new StringBuilder();
stringBuilder.Append(string.Format("{0} {1}", html.RadioButtonFor(expression, true).ToHtmlString(), "Yes"));
stringBuilder.Append(string.Format("{0} {1}", html.RadioButtonFor(expression, false).ToHtmlString(), "No"));
return MvcHtmlString.Create(stringBuilder.ToString());
}
Then you should be able to get back your datas as an IList in your posted action.
Upvotes: 1