如何在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();
发布于 2018-08-24 06:28:10
通常,你不需要操作控件的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);
}
}
https://stackoverflow.com/questions/51991611
复制相似问题