gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:16:29 25 4
gpt4 key购买 nike

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

我正在从数据库中存储的列表填充单选按钮控件。item.MyColumn 具有单选按钮选项列表,例如"is"、“否”、“不适用”等。

在 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();

最佳答案

通常,您不需要操作控件的 ID。如果您想分配默认值,请将其分配给ReceivingMemination

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

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

关于javascript - 如何在 ASP.NET MVC 中为单选按钮列表分配默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51991611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com