简体   繁体   中英

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

I have a ViewData["Mother"] and which contains data of Mother entity. I want to set the relevant option element of the drop-down list to selected according to the value in my ViewData["Mother"] . As an example - if ViewData["Mother"] is Buddhism , the option element which contains Buddhism value should be set to selected .

Mother.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();
}

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

You can use jquery to get the value of ViewData["Mother"] and let select control to select that value by default.

Change your view like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM