This
article will show you how you can binding radiobuttonlist or radiobutton in
asp.net mvc using model or Radiobuttonlist
in MVC 5 using Model, Radiobuttonlistfor values.
So for this article first we will create a new asp.net mvc application add a model class file in it. After that we will add the below code.
So for this article first we will create a new asp.net mvc application add a model class file in it. After that we will add the below code.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC_Demos.Models
{
public class RadioButtonLiatModel
{
public List<RadioButtonData>
RadioButtonListData { get; set; }
}
public class RadioButtonData
{
public int Id { get; set; }
public string Value { get; set; }
}
}
|
After this
we will add a controller class file and add the below code into the controller
class file.
public class RadioButtonListController
: Controller
{
//
// GET: /RadioButtonList/
public ActionResult
Index()
{
RadioButtonLiatModel
_radiobuttonliatmodel = new RadioButtonLiatModel();
_radiobuttonliatmodel.RadioButtonListData = new List<RadioButtonData>();
_radiobuttonliatmodel.RadioButtonListData.Add(new RadioButtonData { Id
= 1, Value = "Item 1" });
_radiobuttonliatmodel.RadioButtonListData.Add(new RadioButtonData { Id
= 2, Value = "Item 2" });
_radiobuttonliatmodel.RadioButtonListData.Add(new RadioButtonData { Id
= 3, Value = "Item 3" });
_radiobuttonliatmodel.RadioButtonListData.Add(new RadioButtonData { Id
= 4, Value = "Item 4" });
return
View(_radiobuttonliatmodel);
}
}
|
In above
code I have created a list of data with model and return into the view. After this
we will create the view and add the below code.
@model MVC_Demos.Models.RadioButtonLiatModel
@{
ViewBag.Title
= "Binding Radio Button List in
Asp.Net MVC Using Model";
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
}
<h2>RadioButton List</h2>
<br />
@foreach (var item in Model.RadioButtonListData)
{
<input type="radio" id="@item.Id" value="@item.Id" name="radiobutton" />@item.Value
}
|
Here in
above code you need to take care of one thing. Just check the highlighted part
of the code this is containing the name of the control. This should be common
for all the radio button, because if we don’t have common radio button name then
we will not be able to select the single radio button as per it’s nature.
Now we have
done run the application and check the output.
0 comments:
Please let me know your view