如何在ASP.NET MVC中为单选按钮列表分配默认值?

时间:2018-08-23 17:52:06

标签: javascript asp.net-mvc

如何在JavaScript中获取.Net MVC模型值?

我正在从数据库中存储的列表中填充单选按钮控件。 item.MyColumn包含“是”,“否”,“不适用”等单选按钮选项的列表。

在jQuery中,我需要获取Yes(或)No(或)NA的值,并基于该值,我必须进行一些验证。

<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>

在JavaScript中具有此语法,因此为我提供了:id。而不是与ID关联的值。

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

1 个答案:

答案 0 :(得分:1)

通常,您不需要操纵控件的ID。如果要分配默认值,则将其分配给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>

型号

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

控制器

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);
    }
}