簡體   English   中英

如何根據ViewData中的值將下拉列表的選項元素更改為選中?

[英]How to change option element of the drop-down list in to selected according to the value in ViewData?

我有一個ViewData["Mother"] ,其中包含 Mother 實體的數據。 我想根據我的ViewData["Mother"]中的值將drop-down list的相關option元素設置為selected 例如 - 如果ViewData["Mother"]Buddhism ,則包含Buddhism值的option元素應設置為selected

母親.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; }
}

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

您可以使用jquery獲取 ViewData["Mother"] 的值,並讓 select 控制 select 默認值。

像這樣改變你的觀點:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM