问题
I used Html.RadioButtonFor for item selection in list but it causes name attribute conflict. here is my sample model
public class DataList {
public List<Videos> { set; get;}
}
public class Videos {
public int isSelected {set; get;}
public int id {set; get;}
public string Title { set; get;}
---
}
View template will look like this
@for (var i = 0; i <= Model.DataList.Count - 1; i++)
{
<label class="radio">@Html.RadioButtonFor(m =>Model.Videos[i].isSelected, Model.Videos[i].id)</label>
}
But this cause name attribute conflict (multiple options selected instead of single)
Can anyone help me fix this problem.
回答1:
My issue fixed by shifting isSelected attribute from list to model as only one option selected at a time therefore no need to use within list.
Modified model will look like this.
public class DataList {
public int isSelected {set; get;}
public List<Videos> Videos { set; get;}
}
public class Videos {
public int id {set; get;}
public string Title { set; get;}
---
}
Modified view will look like this
@for (var i = 0; i <= Model.DataList.Count - 1; i++)
{
<label class="radio">@Html.RadioButtonFor(m =>Model.isSelected, Model.Videos[i].id)</label>
}
Now this code works fine perfectly with both radio button selection and posting data.
回答2:
Since the input controls are generated on item object instead of bound Model expression; due to the incorrect expression, name of controls are generated appropriately in html. That's why on post back the value will not be passed to server in ModelState. I have corrected your view code. Please refer below:
@{
var counter = 0;
}
@foreach (var Item in Model.DataList)
{
<tr>
<td>
@Html.HiddenFor(m => m.DataList[counter].LanguageID)
@Item.CultureName
</td>
<td>
@if (Item.isDefault == 1)
{
@Html.RadioButtonFor(m => m.DataList[counter].isDefault, Model.DataList[counter].Default, new { @checked = "checked" })
}
else
{
@Html.RadioButtonFor(m => m.DataList[counter].isDefault, Model.DataList[counter].Default, new { })
}
</td>
</tr>
counter++;
}
回答3:
You can use checkboxes and get the same user interface as radio buttons. You just need to add some javascript to unselect the other checkboxes.
@for (var i = 0; i < Model.DataList.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(m => Model.DataList[i].LanguageID)
@Model.DataList[i].CultureName
</td>
<td>
@Html.CheckBoxFor(m => Model.DataList[i].Default, new { @class="check-radio" })
</td>
</tr>
}
<script type="text/javascript">
$(function () {
$('.check-radio').change(function () {
if ($(this).is(':checked')) {
$('.check-radio').prop("checked", false);
$(this).prop("checked", true);
}
});
});
</script>
来源:https://stackoverflow.com/questions/33440715/selected-radio-button-value-not-passing-with-postback-data-in-mvc-5