首页 > 解决方案 > 如何根据ViewData中的值将下拉列表的选项元素更改为选中?

问题描述

我有一个ViewData["Mother"],其中包含母亲实体的数据。我想根据 my 中的值设置to的相关option元素。举个例子——如果是,包含值的元素应该被设置为。drop-down listselectedViewData["Mother"]ViewData["Mother"]BuddhismoptionBuddhismselected

母亲.cs

public class Mother
{
    [Key,Required,Display(Name = "NIC"),MaxLength(12)]
    public string NIC { get; set; }
    [Required,Display(Name = "Full Name"),MaxLength(100)]
    public string FName { get; set; }
    [MaxLength(15)]  public string Religion { get; set; }
}

控制器.cs

public IActionResult Index(string id)
{
    if (!string.IsNullOrEmpty(id))
    {
       var Mother = _context.Mothers.Where(p => p.NIC == id).FirstOrDefault();
       ViewData["Mother"] = Mother;
    }
    else
    {
        var Mother = _context.Mothers.Where(p => p.NIC == "5861V").FirstOrDefault();
        ViewData["Mother"] = Mother;
    }
    return View();
}

索引.cshtml;

@{ var m = ViewData["Mother"] as School_Mgt.Models.Students.Mother; }
@section Scripts{<script> $(function () { $("select#ReligionM").val("@m.Religion");})</script>}
<label asp-for="ReligionM">Religion</label>
<select asp-for="ReligionM" name="ReligionM" >
    <option>Please select your Religion</option>
    <option value="Buddhism">Buddhism</option>
    <option value="Catholic">Catholic</option>                                                  
</select> 
...                                           

标签: c#asp.net-core

解决方案


您可以使用jquery获取 ViewData["Mother"] 的值,并让选择控件默认选择该值。

像这样改变你的观点:

@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Index</h1>

@{ var m = ViewData["Mother"] as School_Mgt.Models.Students.Mother;  }
@section Scripts{
    <script>
        $(function () {
            $("select#ReligionM option").each(function () {
                if ($(this).val()== "@m.Religion") {
                    $("select#ReligionM").val("@m.Religion");
                }
            }) 
        })</script>
}
<label asp-for="FNameM">Name in full</label>
<input asp-for="FNameM" name="FNameM" type="text" value="@m.FName">

<label asp-for="ReligionM">Religion</label>
<select asp-for="ReligionM" name="ReligionM">
    <option>Please select your Religion</option>
    <option value="Buddhism">Buddhism</option>
    <option value="Catholic">Catholic</option>
</select>  

推荐阅读