I have a list of users I am retrieving from Active Directory like so
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DOMAIN", "dc=domain,dc=org");
GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, "Advisors");
ViewBag.EmployeeID = new SelectList(group.Members, "EmployeeID", "DisplayName");
I would like to add two additional items to this list but do not want to create user accounts for them in Active Directory as they are not real users.
Is it possible to do something like
var items1 = new[]
{
new { EmployeeID = "1", DisplayName = "Independent" },
new { EmployeeID = "2", DisplayName = "Own" }
};
var items = Concat(group.Members, items1);
{
ViewBag.EmployeeID = new SelectList(items, "EmployeeID", "DisplayName");
}
Well, You can have a ViewModel like this:
public class EmployeeViewModel
{
public string EmployeeId { get; set; }
public string DisplayName { get; set; }
}
and than you can cast the group.Members to a list of your ViewModel, add some custom itens on this list and set this list to the ViewBag.
var members = group.Members.Select(x => new EmployeeViewModel() { EmployeeId = x.EmployeeId, DisplayName = x.DisplayName }).ToList();
members.Add(new EmployeeViewModel() { EmployeeId = "1", DisplayName = "Independent" });
members.Add(new EmployeeViewModel() { EmployeeId = "2", DisplayName = "Own" });
ViewBag.EmployeeID = new SelectList(members, "EmployeeID", "DisplayName");
Related
How do i put a placeholder on my #Html.Dropdownlist that is not selectable.
I implemented chosen-jquery on my dropdown.
My code is as per below:
#Html.DropDownList("Id", new SelectList(new Ahib.Membership.UserFacade().GetAllUsers(), "Id", "Username"), "-select a system owner-", new { #class="chosen1-select" })
Currently my dropdownlist has a placeholder but the "-select a system owner-" becomes a selectable value which i dont want. How do solve this issue?
You can convert your list to the selectitem list and apply your disabled attribute from the controller itself.
like this
assuming your model is like this
class user
{
public int Id { get; set; }
public string Username { get; set; }
}
Convert your list to List<SelectListItem> like this, note here I am disabling the select a system owner entry.
public ActionResult Index()
{
List<user> users = new List<user>();
users.Add(new user { Id = 1, Username = "test1" });
users.Add(new user { Id = 2, Username = "test2" });
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "-select a system owner-", Value = "0", Disabled = true });
foreach (var item in users)
{
list.Add(new SelectListItem
{
Text = item.Username,
Value = item.Id.ToString()
});
}
ViewBag.listItems = list;
return View();
}
and in view use it like this
#Html.DropDownList("test", ViewBag.listItems as IEnumerable<SelectListItem>);
Result:
I have three dropdown list:
#Html.DropDownListFor(m => m.Edit.SelectCountryId, Model.Edit.Countries, "Please select", new { id = "CountryID", #class = "form-control", #onchange = "LoadRegions();" })
#Html.DropDownListFor(m => m.Edit.SelectRegionId,Model.Edit.Region, "Please select", new { id = "RegionID", #class = "form-control", #onchange = "LoadCities();" })
#Html.DropDownListFor(m => m.Edit.SelectCityId, Model.Edit.City, "Please select", new { id = "CityID", #class = "form-control" })
I populate second one depending on first one and third depending on second...but when i want to display those dropdown lists for some specific user im able to display just countries
My model:
public int SelectCountryId { get; set; }
public int SelectRegionId { get; set; }
public int SelectCityId {get; set;}
public System.Web.Mvc.SelectList City { get; set; }
public System.Web.Mvc.SelectList Region{ get; set; }
public System.Web.Mvc.SelectList Country{ get; set; }
My controller:
model.Edit.SelectCountryId = user.ContactInformation.First().City.Region.Country.Id;
model.Edit.SelectRegionId = user.ContactInformation.First().City.Region.Id;
model.Edit.SelectCityId = user.ContactInformation.First().City.Id;
I get values on controller but i cant get display them in view
EDIT:
My scripts:
var region = $('#RegionID');
var urlCountries = "/Account/GetRegions";
$.getJSON(urlCountries, { countryId: $('#CountryID').val() }, function (response) {
// clear and add default (null) option
region.empty().append($('<option></option>').val('').text('Please select'));
for (var i = 0; i < response.length; i++) {
region.append($('<option></option>').val(response[i].Id).text(response[i].Name));
}
});
var city = $('#CityID');
var url = "/Account/GetCities"; // use the helper (dont hard code)
$.getJSON(url, { regionId: $('#RegionID').val() }, function (response) {
// clear and add default (null) option
city.empty().append($('<option></option>').val('').text('Please select'));
for (var i = 0; i < response.length; i++) {
city.append($('<option></option>').val(response[i].Id).text(response[i].Name));
}
});
My methods for GetCity() and GetRegions()
public IEnumerable<IRegion> GetRegions(int countryId)
{
Model.Administration.Region[] modelRegions = Model.Administration.Region.FindAll(DetachedCriteria.For<Model.Administration.Region>().Add(Restrictions.Eq("Country.Id", countryId)));
return modelRegions.Select(Region.ConvertFromModel).Cast<IRegion>().ToList();
}
public IEnumerable<ICity> GetCities(int regionId)
{
CityLimited[] modelCities = CityLimited.FindAll(DetachedCriteria.For<CityLimited>().Add(Restrictions.Eq("Region.Id", regionId)));
return modelCities.Select(City.ConvertFromModel).Cast<ICity>().ToList();
}
You need to pass an additional value indicating the selected option in the json data your returning to the view. Your GetRegions() method should look like
public JsonResult GetRegions(int countryId) // return a JsonResult
{
Model.Administration.Region[] modelRegions = Model.Administration.Region.FindAll(DetachedCriteria.For<Model.Administration.Region>().Add(Restrictions.Eq("Country.Id", countryId)));
var options = modelRegions.Select(Region.ConvertFromModel).Cast<IRegion>().ToList();
var selection = 1; // set the value of the selected option here - must match the `ID` property of one of one of the `IRegion` your returning
return Json(new { options = options, selection = selection }, JsonRequestBehavior.AllowGet);
}
Side note: Its not clear what modelRegions.Select(Region.ConvertFromModel).Cast<IRegion>().ToList(); returns but if IRegion contains more that just the ID and Name properties you need for the view, consider creating a collection of anonymous objects so you don't send unnecessary data across the wire
Then the corresponding script should be
var url = '#Url.Action("GetRegions", "Account")'; // use the helper (dont hard code)
var regions = $('#RegionID'); // cache the element
$('#CountryID').change(function() {
$.getJSON(url, { id: $(this).val() }, function(response) {
// clear and add default (null) option
regions.empty().append($('<option></option>').val('').text('Please select'));
$.each(response.options, function(index, item) {
cities.append($('<option></option>').val(item.Value).text(item.Text));
});
regions.val(response.selection); // set the selected value
});
});
and remove the #onchange = "LoadRegions(); from you markup
Ditto for the GetCities() controller method and the corresponding script
HI i am new to mvc and bootstrap.. i want to dynamically add two text box at run time in mvc4 and bootstrap.. i have tried many sites but i am not able to understand. please give me simple example
i have tried this
In model
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
}
in controller
public ActionResult PanelEx()
{
var initialData = new[] {
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
what should i wrote in model. how to do next step..i am stuck PLese help
public ActionResult PanelEx()
{
var initialData = new List<Gift>{
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
#model IEnumerable<Gift>
<div>
#foreach(var item in Model)
{
<div>
#Html.TextBoxFor(item=>item.Name)
</div>
}
</div>
{Sorry new to JSON}
I need to build up an array of resources (Users) and pass it in to my view, might be a better way than what ive done below? (Demo)
My model is simply
public class ScheduleUsers
{
public string Resource{ get; set; }
}
On my controller
var users = new JsonArray(
new JsonObject(
new KeyValuePair<string,JsonValue>("id","1"),
new KeyValuePair<string,JsonValue>("name","User1")),
new JsonObject(
new KeyValuePair<string, JsonValue>("id", "2"),
new KeyValuePair<string, JsonValue>("name", "User2"))
);
model.Resources = users.ToString();
Why don't you just return a list of entities as a JSON result, like:
public class CarsController : Controller
{
public JsonResult GetCars()
{
List<Car> cars = new List<Car>();
// add cars to the cars collection
return this.Json(cars, JsonRequestBehavior.AllowGet);
}
}
It will be converted to JSON automatically.
I did this and this works
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
//Serialize
js.Serialize(GetResources(), sb);
public List<ScheduledResource> GetResources()
{
var res = new List<ScheduledResource>()
{
new ScheduledResource()
{
id = "1",
color = "blue",
name = "User 1"
},
new ScheduledResource()
{
id = "2",
color = "black",
name = "User 2"
},
};
return res;
}
I am having problems with getting a DropDownList to correctly select the right value and display it.
I am using the following:
#Html.DropDownListFor(x => Model.AdminSummaries[index].Status, AdminStatusReference.GetAdminStatusOptions(), new { id = string.Format("Status_{0}",index ) })
Is it okay that AdminStatusReference.GetAdminStatusOptions() returns a List or MUST it return an IEnumerable?
Model:
public class MyViewModel
{
public IList<AdminSummary> AdminSummaries { get; set; }
}
public class AdminSummary
{
public string Status { get; set; }
}
public static class AdminStatusReference
{
public static IEnumerable<SelectListItem> GetAdminStatusOptions()
{
return new[]
{
new SelectListItem { Value = "1", Text = "status 1" },
new SelectListItem { Value = "2", Text = "status 2" },
new SelectListItem { Value = "3", Text = "status 3" },
};
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
AdminSummaries = new[]
{
// preselect the first item
new AdminSummary { Status = "1" },
// preselect the second item
new AdminSummary { Status = "2" },
// nothing will be preselected because there is no xxx Value in the list
new AdminSummary { Status = "xxx" },
}.ToList()
};
return View(model);
}
}
View:
#model MyViewModel
#for (int index = 0; index < Model.AdminSummaries.Count; index++)
{
#Html.DropDownListFor(
x => x.AdminSummaries[index].Status,
new SelectList(
AdminStatusReference.GetAdminStatusOptions(),
"Value",
"Text",
Model.AdminSummaries[index].Status
)
)
}
It will be fine.
List<T> implements IEnumerable<T>
for using
#Html.DropDownListFor<>
in my projects I have always used a IEnumerable<SelectListItem> in my View and therefore before hand I have set which item has the propery "Selected" as true. This will then set the default item.
forgot I could edit my original answer :P
here is the html rendered on my project