goofyui
goofyui

Reputation: 3492

How to assign default value to Radio Button List in ASP.NET MVC?

How to fetch .Net MVC Model value in the JavaScript?

I am populating the Radio Button Control from the list stored in the database. item.MyColumn has the list of Radio button options such as Yes, No, NA etc.

In the jQuery, I need to fetch the value of Yes (or) No (or) NA and based on that value, I have to do some validation.

<div class="col-sm-8 checkbox-inline text-left">
    @foreach (var item in Model.YesNoNAList)
    {
        @Html.RadioButtonFor(model => model.ReceivingMedication, item.ID, new { @id = "ReceivingMedication" + item.MyColumn }) @:  @item.MyColumn
    }
    <span asp-validation-for="ReceivingMedication" class="text-danger"></span>
</div>

Having this syntax in the JavaScript, gives me the column : id . And not the value associated with the Id.

   var selValue = $('input[name=ReceivingMedication]:checked').val();

Upvotes: 0

Views: 1590

Answers (1)

Win
Win

Reputation: 62290

Normally, you do not need to manipulate the control's ID. If you want to assign default value, you assign it to ReceivingMedication.

<div class="col-sm-8 checkbox-inline text-left">
    @foreach (var item in Model.YesNoNAList)
    {
        <p>@Html.RadioButtonFor(model => model.ReceivingMedication, item.Value) @item.Text</p>
    }
    <span asp-validation-for="ReceivingMedication" class="text-danger"></span>
</div>

<script>
    var selValue = $('input[name=ReceivingMedication]:checked').val();
    console.log(selValue);
</script>

Model

public class Model
{
    public List<SelectListItem> YesNoNAList { get; set; }
    public string ReceivingMedication { get; set; }
    public string ID { get; set; }
}

Controller

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new Model
        {
            YesNoNAList = new List<SelectListItem>
            {
                new SelectListItem {Text = "Yes", Value = "1"},
                new SelectListItem {Text = "No", Value = "0"},
                new SelectListItem {Text = "N/A", Value = ""}
            },
            ReceivingMedication = "0" // Default value
        };
        return View(model);
    }
}

Upvotes: 1

Related Questions