Bind RadioButton from Database using ViewData (without Model) in ASP.Net MVC

Last Reply 5 months ago By dharmendr

Posted 5 months ago

hello,

i have this code in mvc to bind drop down list from database

@Html.DropDownList("MySkills", (IEnumerable<SelectListItem>)ViewData["Class"])

 controller 

var fromdb = new SelectList(db.StudentClasses.ToList(), "StudentClassID", "ClassName");
ViewData["Class"]= fromdb;

instead of dropdownlist i want to bind the return list in radio button

pls advice i do not want to use model just need to replace the dropdown with radio button 

Posted 5 months ago

Hi nauna,

Check this example. Now please take its reference and correct your code.

Database

For this example i have used table named Fruits.

You can download the database table SQL by clicking the download link below.

Download SQL file

Controller 

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        FruitsEntities db = new FruitsEntities();
        var fromdb = new SelectList(db.Fruits.ToList(), "FruitId", "FruitName");
        ViewData["Fruits"] = fromdb;
        var from = db.Fruits.ToList();
        ViewData["Radio"] = from;
        return View();
    }
}

View

<div>
    <%:Html.DropDownList("Fruit", (IEnumerable<SelectListItem>)ViewData["Fruits"])%>
    <br />
    <%for (int i = 0; i < ((List<Fruit>)ViewData["Radio"]).Count; i++)
        {%>
    <%:Html.RadioButton("Fruit", ((List<Fruit>)ViewData["Radio"])[i].FruitId, false)%>
    <%=((List<Fruit>)ViewData["Radio"])[i].FruitName%>
    <br />
    <% } %>
</div>

Screenshot