How to check Guid.Empty identifier in client side dropdown list

I have the following ViewResult() that populates the model (by holding two drop-down lists), which, in turn, are sent to the strongly typed view (). Notice how I add the new value "--- VIEW ALL ---" in both drop-down lists with Id being 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); } 

Inside the view (), I jquery .change() event for the first dropdown, and I want to define the selected value.

Based on the selected value, I need to take different actions. For example, if Guid.Empty , then do it ... if not, then to this ...

So far, the code that I have in the .change () event looks like this:

 $('#ApplicationId').change(function () { if ($(this).val() === "00000000-0000-0000-0000-000000000000") { alert("aaa"); } else { alert("xxx"); } }); 

The code works, but I find it ugly to check Guid.Empty way I do it.

Does anyone have a different / better approach to achieve this?

Thanks in advance!

Regards Vlince

PS: Since it will be a multilingual application, I can not use the selected text drop-down list to compare if (...).

+4
source share
1 answer

I am assuming Model.ApplicationList and Model.RoleList are a List type such as List<SelectListItem> and not IEnumerable. If so, why not add an empty, "--- View All ---" when you create a SelectList and use an empty string for the value.

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

And your javascript

 $('#ApplicationId').change(function () { if ($(this).val() === "") { alert("aaa"); } else { alert("xxx"); } }); 
0
source

All Articles