irfanmcsd irfanmcsd - 2 months ago 30
ASP.NET (C#) Question

Selected radio button value not passing with postback data in MVC 5

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.

Answer

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.

Comments