我有以下ViewResult()
,它填充一个模型(包含两个下拉列表),然后将其发送到强类型View()。
请注意我如何在两个下拉列表中添加新的“---VIEW ALL---”值,其中 Id 为 Guid.Empty。
[HttpGet]
public ViewResult ManageUsers()
{
var applicationList = _facade.Value.GetApplications().OrderBy(a => a.Name).ToList();
applicationList.Add(new Application() { Id = Guid.Empty, Name = "---VIEW ALL---" });
var roleList = _facade.Value.GetRoles(applicationList.First().Id).OrderBy(a => a.Name).ToList();
roleList.Add(new Role() { Id = Guid.Empty, Name = "---VIEW ALL---" });
var model = new ManageUsersModel();
model.ApplicationList = new SelectList(applicationList, "Id", "Name", applicationList.First().Id);
model.RoleList = new SelectList(roleList, "Id", "Name");
return View(model);
}
进入 View() 后,我为第一个下拉列表创建一个 jquery .change()
事件,并且我希望检测所选值。
根据所选值,我需要采取不同的操作。例如,如果选择了 Guid.Empty 值,则执行此操作……如果没有,则执行此操作……
到目前为止,我在 .change() 事件中的代码如下所示:
$('#ApplicationId').change(function () {
if ($(this).val() === "00000000-0000-0000-0000-000000000000") {
alert("aaa");
}
else {
alert("xxx");
}
});
代码可以工作,但我发现按照我的方式检查Guid.Empty
丑。
有人有不同/更好的方法来实现这一目标吗?
提前致谢!
真诚的 弗林斯
PS:由于这将是一个多语言应用程序,因此我无法使用下拉列表中的所选文本
进行 if(...) 比较。
最佳答案
我假设 Model.ApplicationList 和 Model.RoleList 是一种列表,例如 List<SelectListItem>
而不是 IEnumerable。如果是这样,为什么不在创建 SelectList 时附加空的“---View All---”并使用空字符串作为值。
[HttpGet]
public ViewResult ManageUsers()
{
var applicationList = _facade.Value.GetApplications().OrderBy(a => a.Name).ToList();
var roleList = _facade.Value.GetRoles(applicationList.First().Id).OrderBy(a => a.Name).ToList();
var model = new ManageUsersModel();
model.ApplicationList = new SelectList(applicationList, "Id", "Name", applicationList.First().Id);
model.RoleList = new SelectList(roleList, "Id", "Name");
var defaultChoice = new SelectListItem("", "---VIEW ALL---")
model.ApplicationList.InsertAt(0, defaultChoice);
model.RoleList.InsertAt(0, defaultChoice);
return View(model);
}
还有你的 JavaScript
$('#ApplicationId').change(function () {
if ($(this).val() === "") {
alert("aaa");
}
else {
alert("xxx");
}
});
关于jquery - 如何检查客户端下拉列表的 Guid.Empty Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15952930/