如何检查客户端下拉列表的Guid.Empty Id

时间:2013-04-11 15:32:40

标签: jquery asp.net-mvc-4

我有以下ViewResult()填充模型(持有两个下拉列表),然后将其发送到强类型的View()。 请注意我如何在 Id Guid.Empty.

的两个下拉列表中添加新的“ --- VIEW ALL --- ”值
[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我正在做的方式。

有没有人有不同/更好的方法来实现这一目标?

提前致谢!

此致 Vlince

PS:由于这是一个多语言应用程序,我不能使用if(...)比较的下拉列表的selected text

1 个答案:

答案 0 :(得分:0)

我假设Model.ApplicationList和Model.RoleList是一种类型的List,例如List<SelectListItem>而不是IEnumerable。如果是这样,为什么不在创建SelectList时附加空的“---查看全部---”并使用空字符串作为值。

[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");
    }
});