c# - 如何根据ViewData中的值将下拉列表的选项元素更改为选中?
问题描述
我有一个ViewData["Mother"]
,其中包含母亲实体的数据。我想根据 my 中的值设置to的相关option
元素。举个例子——如果是,包含值的元素应该被设置为。drop-down list
selected
ViewData["Mother"]
ViewData["Mother"]
Buddhism
option
Buddhism
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; }
}
控制器.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"] 的值,并让选择控件默认选择该值。
像这样改变你的观点:
@{
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>
推荐阅读
- websphere - 删除 WebSphere Portal Server 的 SelfCare portlet 中的 editProfile.jsp 页面的影响
- python - 使用请求模块在 Python 中的 Http Post 请求中超出最大重试次数和证书验证失败
- shell - 用于批量替换 .csv 文件中的特定字符串的 shell 脚本
- javascript - 为函数创建单独的类
- vue.js - 在 v-for 循环中的某些元素上悬停在 vue 应用程序中
- javascript - 可折叠面板和空间填充
- javascript - 删除 index.html 中的 url 但我怎样才能在 app.component.ts 中拥有它们
- css - 物化模块构建失败:无效的 CSS/预期的选择器
- elixir - 如何将列表从一种格式更改为另一种格式
- html - 有没有办法在 hybris 6.7 中托管 HTML?