Populating ASP.NET MVC DropDownList - asp.net-mvc

OK, I've been Googling for hours and trying everything and can't get anything to work. I am learning MVC using Sharp Architecture and have generated some basic forms for creating Client objects. I want to fill the state drop down list with a list of US states and let the user pick from that list. I am able to populate the list and get the value back (to save the client) but when I go to edit the client, the client's current state is not selected. I have set the selected value in the SelectList:
<li>
<label for="Client_StateProvince">StateProvince:</label>
<div>
<%= Html.DropDownListFor(c=>c.Client.StateProvince, new SelectList(Model.StateProvinces, "id", "Name", Model.Client.StateProvince), "-- Select State --")%>
</div>
<%= Html.ValidationMessage("Client.StateProvince")%>
</li>
This does not seem to be good enough. What am I missing?

<%= Html.DropDownListFor(c => c.Client.StateProvince.Id,
new SelectList(Model.StateProvinces,
"id",
"Name",
Model.Client.StateProvince),
"-- Select State --")%>
This does it.
Hope this helps someone else.
~Lee

Worked perfectly for me thanx! I used it to set a parent relation on a subcategory:
<%= Html.DropDownListFor(
model => model.Category.ParentId,
new SelectList(Model.Categories,
"CategoryId",
"Name",
Model.Categories.Where(x => x.CategoryId == Model.Category.ParentId).Single()))%>
Jeroen

I did it this way. Works well.
Controller
IFarmModelInterface service2 = new FarmModelRepository();
ViewData["Farms"] = new SelectList(service2.GetFarmNames(), "id", "FarmName", "XenApp");
View
<%: Html.DropDownListFor(m => m.Farm, (ViewData["Farms"] as SelectList)) %>

public ActionResult AllUsers()
{
List<Users> users = userRep.GetUsers();
var listUsers = (from u in users.AsEnumerable()
select new SelectListItem
{
Text = u.UserName,
Value = u.UserId.ToString(),
Selected = (u.UserId==6)
}).AsEnumerable();
ViewBag.ListItems = listUsers;
//ViewBag.SelectedItem = 2;
return View();
}
In AllUsers.cshtml
<p>#Html.DropDownList("ListItems")</p>

<%= Html.DropDownListFor(c => c.Client.StateProvince, new SelectList(Model.StateProvinces, "Id", "Name")) %>
and override ToString() for StateProvince to return Id, i.e.:
return Id.ToString();
This works but is not a perfect solution...
Dennis

This is View - MVC Controller
#Html.DropDownListFor(m => m.Entity, new ABC.Models.DropDownPopulate().MyMethod, new { #class = "form-control input-inline input-medium" })
MyMethod Get Data List Bind With Dropdown Using SelectListItems
public List<SelectListItem> MyMethod
{
get
{
List<SelectListItem> dropdownList = new List<SelectListItem>();
var items = new DropDown_Bl().GetAll();
foreach (var item in items)
{
SelectListItem dropdownItem = new SelectListItem();
dropdownItem.Value = item.RnID.ToString();
dropdownItem.Text = item.Description;
dropdownList.Add(dropdownItem);
}
dropdownList.Insert(0, new SelectListItem() { Text = "Please Select", Value = "", Selected = true });
return dropdownList;
}
}
GetAll Method In Dropdown_Bl - Used to get data as list from database
public List<My_Table> GetAll()
{
var Items = _Context.MyRepository.GetMany(q => q.Area == "ASD").ToList();
return Items ;
}

public ActionResult AllUsers() {
List<Users> users = userRep.GetUsers();
var listUsers = (from u in users.AsEnumerable()
select new SelectListItem
{
Text = u.UserName,
Value = u.UserId.ToString(),
Selected = (u.UserId==6)
}).AsEnumerable();
// ViewBag.ListItems = listUsers;
ViewData["tempEmpList"]=listUsers;
return View(); }
Fill Dropdown
#Html.DropDownList("SelectedEmployee", new SelectList((IEnumerable) ViewData["tempEmpList"], "Id", "Name"))

Related

Simple Dropdown list in Edit MVC 4

I have simple table with users, which have edit column, so when you click it, you can edit this specific row. One of columns in my tables is TimeZone, so you can choose in which time zone you are. So proper way to create edit filed is Dropdown list.
So I find this code and implemented it in my controller:
public ActionResult Edit(int id = 0)
{
using (var dbVn = new userDbEntities())
{
var edit = dbVn.UsersTables.Find(id);
if (edit == null)
{
return HttpNotFound();
}
SelectListItem item;
var zoneList = new List<SelectListItem>();
item = new SelectListItem();
item.Text = "TimeZone1";
item.Value = "1";
zoneList.Add(item);
item = new SelectListItem();
item.Text = "TimeZone2";
item.Value = "2";
zoneList.Add(item);
ViewBag.ZoneT = zoneList;
return View(edit);
}
}
And in my view I have this:
<div class="editor-field">
#Html.DropDownListFor(model => model.TimeZoneId, new SelectList((IEnumerable<SelectListItem>)ViewBag.ZoneT, "Value", "Text", "1"))
#Html.ValidationMessageFor(model => model.TimeZoneId)
</div>
This works fine if we would have a few items (3 to 4). But if we have a list of timezonese (96), is proper to use datatable (TimeZoneTable).
Any Idea how to implement it in above code in controller...

How to work with DropDownListFor in an EDIT view

Hi I have a problem with DropDownListFor on the Edit view.
Basically I'm using a partial view which contains my form and in my Edit and Create view I call this partial view.
I have around 5 similiar DropdownlistFor and these work well on create action but in edit doesn't, mainly i'm not getting (unable) to set the selected value.
In my Edit Action (GET), I fill my property ViewModel if the true object has the property filled.
if(icb.BAOfficer != null)
editICB.BAOfficer = icb.BAOfficer;
List<Staff> staffs = _fireService.GetAllStaffs().ToList();
staffs.Insert(0, new Staff { StaffId = -1, Name = "" });
editICB.BAOfficers = staffs;
return View(editICB);
This is how I'm filling my drop down and how I'm trying to set the selected value.
#Html.DropDownListFor(model => model.BAOfficerSelected, new SelectList(Model.BAOfficers, "StaffId", "Name", (Model.BAOfficer!= null ? Model.BAOfficer.StaffId:-1)), new { #class = "rounded indent" })
#Html.ValidationMessageFor(model => model.BAOfficer.StaffId)
I solve the problem setting a value to my model.BAOfficerSelected in Edit Action, this was the (easy) secret.
I need the first item like a empty option because is not a required information, but on the edit view if has value I need to set it as selected option.
In the end, it was my code.
My Model
public int BAOfficerSelected { get; set; }
public SelectList BAOfficers { get; set; }`
My Controller Create/Edit Action
if (icb.BAOfficer != null) // only for edit action
editICB.BAOfficerSelected = icb.BAOfficer.StaffId; //this will set the selected value like a mapping
//for Edit and Create
List<Staff> staffs = _fireService.GetAllStaffs().ToList();
staffs.Insert(0, new Staff { StaffId = -1, Name = "" });
editICB.BAOfficers = new SelectList(staffs, "StaffId", "Name");
return View(editICB);`
My View
#Html.DropDownListFor(model => model.BAOfficerSelected, Model.BAOfficers, new { #class = "rounded indent" })
I hope this can help others.
The best and cleanest way of doing this is setting the selected value in server side, in the SelectList object.
So, if your BAOfficerSelected is nullable... it is all simpler: You don't need to rely in adding a dummy item to hold the -1 for not selected value.
Instead, you do it this way:
List<Staff> staffs = _fireService.GetAllStaffs().ToList();
editICB.BAOfficers = new SelectList(staffs, "StaffId", "Name", editICB.BAOfficer != null ? editICB.BAOfficer.StaffId : null);
Of course, the BAOfficers need to be changed type from List<Staff> to SelectList.
Then, in your partial view you do:
#Html.DropDownListFor(model => model.BAOfficerSelected, Model.BAOfficers, "Select one...", new { #class = "rounded indent" })
Adding the 3rd parameter is needed to indicate that the default value (if nothing is selected) is that text.
Instead of using a SelectList, I often find it works better to use a List<SelectListItem>.
Further, I usually use an EditorTemplate for my dropdowns to keep my views clean.
So if my select list returns List<SelectListItem>:
public List<SelectListItem> BAOfficers { get; set };
You can set it up like this:
model.BAOfficers = staffs.Select(staff =>
new SelectListItem { Text = staff.Name, Value = staff.StaffId }).ToList();
Then in your EditorTemplate:
<!-- EditorTempaltes\DropDownList.cshtml -->
#model System.String
<p>
#Html.LabelFor(m => m):
#Html.DropDownListFor(m => m, new SelectList(
(List<SelectListItem>)ViewData["selectList"], "Value", "Text",
String.IsNullOrEmpty(Model) ? String.Empty : Model), String.Empty)
#Html.ValidationMessageFor(m => m)
</p>
And then in the view, just pass the SelectList into the EditorTemplate:
#Html.EditorFor(m => m.BAOfficerSelected, "DropDownList",
new { selectList = Model.BAOfficers() })
I met the same problem ,too.
According the article https://dotnetfiddle.net/PIGNLF which way gave a simple way to deal with this problem without two Models or more classes.enter link description here
here is my code
add model
public class NoteSelectLisModel
{
public string Value { get; set; }
public string Name { get; set; }
}
add Controller
public ActionResult Edit(int? _ID)
{
ViewBag.NoteState = new SelectList(new List<NoteSelectLisModel>()
{
new NoteSelectLisModel() {Value="1",Name="A)"},
new NoteSelectLisModel() {Value="2",Name="B"},
new NoteSelectLisModel() {Value ="3",Name ="C"}
}, "Value", "Name", 1);
Table ut = _db.Tables.Find(_ID);
if (ut == null)
{
return HttpNotFound();
}
else
{
return View(ut);
}
}
add View .cshtml
#Html.DropDownListFor(m => m.NOTE, (IEnumerable<SelectListItem>)ViewBag.NoteState, "No Selected")
The edit's Model is the same and the dropdownlist passed by View.bag

Drop down list doesnt show the selected value in edit mode in mvc 2

Hi I am trying to display the database value on the dropdownlist in the edit section, but the drop down list shows the default set value below is my code:
Controller:
public ActionResult Edit(int id)
{
// Product helmet = new Product();//
//Product garrage = new Product();
ViewBag.mode = "edit";
// for dropdown track
ITrackRepository trackResp = new TrackRepository();
IQueryable<Object> tracks = trackResp.GetVenuesSelectlist();
ViewData["Venue"] = new SelectList(tracks, "VenueID", "Name");
// for dropdown for event type
ITrackdayRepository trackdayResp = new TrackdayRepository();
IQueryable<EventType> eventTypes = trackdayResp.GetAllEventTypes();
ViewData["EventTypes"] = new SelectList(eventTypes, "ID", "Name");
// for dropdown experience
IExperienceLevelRepository expLevelResp = new ExperienceLevelRepository();
IQueryable<ExperienceLevel> expLevel = expLevelResp.GetAllExperienceLevels().OrderBy(ExperienceLevel => ExperienceLevel.Name);
ViewData["Experience"] = new SelectList(expLevel, "ID", "Name");
// dropdown for helmets
IProductRepository prodResp = new ProductRepository();
Product productQuantity = prodResp.GetProd(id);
if (productQuantity.ProductTypeID == 1)
{
// dropdown for attendees
var attendees = Enumerable.Range(1, 80).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() });
ViewData["attendees1"] = new SelectList(attendees, "Value", "Text",**productQuantity.QtyAvailable)**; //productQuantity.QtyAvailable is the value from db(selected value of dropdown)
ViewData["txtAttendees"] = productQuantity.UnitCost;
}
else
{
var emptyattendees = Enumerable.Range(1, 80).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() });
ViewData["attendees1"] = new SelectList(emptyattendees.ToList(), "Value", "Text");
} Event trackday = trackdayResp.GetEvent(id); //returns all the values from event table whose eventid is id
//need to return product quantity, value to drop downlist
return View("Create", trackday);
}
View Edited(WOrking):
<% if (ViewBag.mode != "edit")
{ %>
<%: Html.DropDownList("attendees1", ViewData["attendees1"] as SelectList, "--select--")%>
<%}else{%>
<%: Html.DropDownList("attendees1")%>
<%} %>
I had the same problem a month ago, and I solved it by doing this:
ViewData["attendees1"] = new SelectList(attendees, "Value", "Text", productQuantity.QtyAvailable);
I mean, you have to add a 4th parameter with the SelectedValue which you take it from the original value before the edit. You have to do this only in Edit action, no need to do that in Create since it is a new object and no value is selected yet.
And in your markup you define the DropDownList like this:
<%: Html.DropDownList("attendees1") %>
This way the selected value will be selected instead of the default one.
Hope that helps.
EDIT:
Create action method:
ViewData["attendees1"] = new SelectList(attendees, "Value", "Text");
Edit action method:
ViewData["attendees1"] = new SelectList(attendees, "Value", "Text", productQuantity.QtyAvailable);
Markup in both Create and Edit views
<%: Html.DropDownList("attendees1") %>

Challenges with selecting values in ListBoxFor

Working on my first ASP.Net MVC2 web app recently, I came across some issues when I needed to select multiple values in a list box. I worked around it with some jQuery, but went ahead and put together some very simple code to demonstrate. I'm using EF for the model, with two entities - Customers and HelpDeskCalls:
Controller:
public ActionResult Edit(int id)
{
Customer currCustomer = ctx.Customers.Include("HelpDeskCalls").Where(c => c.ID == id).FirstOrDefault();
List<HelpDeskCall> currCustCalls = (ctx.HelpDeskCalls.Where(h => h.CustomerID == id)).ToList();
List<SelectListItem> currSelectItems = new List<SelectListItem>();
List<String> selectedValues = new List<string>();
foreach (HelpDeskCall currCall in currCustCalls)
{
bool isSelected = (currCall.ID % 2 == 0) ? true : false;
//Just select the IDs which are even numbers...
currSelectItems.Add(new SelectListItem() { Selected = isSelected, Text = currCall.CallTitle, Value = currCall.ID.ToString() });
//add the selected values into a separate list as well...
if (isSelected)
{
selectedValues.Add(currCall.ID.ToString());
}
}
ViewData["currCalls"] = (IEnumerable<SelectListItem>) currSelectItems;
ViewData["currSelected"] = (IEnumerable<String>) selectedValues;
return View("Edit", currCustomer);
}
View:
<div class="editor-field">
<%: Html.ListBoxFor(model => model.HelpDeskCalls, new MultiSelectList(Model.HelpDeskCalls, "ID", "CallTitle", (IEnumerable) ViewData["currSelected"]), new { size = "12" })%>
<%: Html.ListBoxFor(model => model.HelpDeskCalls, ViewData["currCalls"] as IEnumerable<SelectListItem>, new { size = "12"}) %>
<%: Html.ListBox("Model.HelpDeskCalls", new MultiSelectList(Model.HelpDeskCalls, "ID", "CallTitle", (IEnumerable)ViewData["currSelected"]), new { size = "12"}) %>
<%: Html.ValidationMessageFor(model => model.HelpDeskCalls) %>
</div>
For this sample, I'm just selecting HelpDeskCall.IDs which are even. I'm trying two different syntaxes for ListBoxFor: One uses an IEnumerable of values for selections, one using an IEnumerable of SelectListItems. By default, when I run this code, no selections are made to either ListBoxFor, but the non-strongly typed ListBox selects correctly.
I read this post on ASP.Net and this thread on SO, but no joy. In fact, if I add the override ToString() to my HelpDeskCall class (as suggested in the ASP.net thread) all values are selected, which isn't right either.
If someone could shed some light on how this should work (and what I'm missing or doing wrong), this then neophyte would be very grateful.
Here's an example illustrating the strongly typed version:
Model:
public class MyViewModel
{
public int[] SelectedItemIds { get; set; }
public MultiSelectList Items { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// Preselect items with id 1 and 3
var selectedItemIds = new[] { 1, 3 };
var model = new MyViewModel
{
Items = new MultiSelectList(
new[]
{
// TODO: Fetch from your repository
new { Id = 1, Name = "item 1" },
new { Id = 2, Name = "item 2" },
new { Id = 3, Name = "item 3" },
},
"Id",
"Name",
selectedItemIds
)
};
return View(model);
}
}
View:
<%: Html.ListBoxFor(x => x.SelectedItemIds, Model.Items) %>
I don't know if this behaviour has changed in the RTM of MVC3 that I'm using, but it seems that selection and binding now works out of the box. The only catch is that the model should contain a property with the IDs, like that :
public class MyViewModel {
public int[] ItemIDs { get; set; }
}
Then the following in the view would work fine, both pre-selecting the correct values and binding correctly during post:
#Html.ListBoxFor(model => model.ItemIDs, (IEnumerable<SelectListItem>)(new[] {
new SelectListItem() { Value = "1", Text = "1" },
new SelectListItem() { Value = "2", Text = "2" }
}))
I have found better workaround. Usual way to preselect select list:
#Html.ListBoxFor(
model => model.Roles,
new MultiSelectList(db.Roles, "Id", "Name")
)
#Html.ValidationMessageFor(model => model.Roles)
Doesn't work.., never ever any option is selected, until:
public ActionResult Edit(int id)
{
var user = db.Users.Find(id);
// this is workaround for http://aspnet.codeplex.com/workitem/4932?ProjectName=aspnet
ViewData["Roles"] = user.Roles.Select(r => r.Id);
return View(user);
}
Selected Roles has to be stored in ViewData, to workaround nasty bug.
Another option is to take advantage of nameof, you could do something like this;
Html.ListBox(nameof(MainProjectViewModel.Projects), Model.Projects)

How to make dropdownlist show a selected value in asp.net mvc?

I have an edit page with a Html.DropDownList in it....I cant show the dropdownlist value it always shows up with Select instead i want to make the dropdown show an item as selected based on a model value say Model.Mes_Id... Any suggestion how it can be done...
<p>
<label for="MeasurementTypeId">MeasurementType:</label>
<%= Html.DropDownList("MeasurementType", // what should i give here?)%>
<%= Html.ValidationMessage("MeasurementTypeId", "*") %>
</p>
EDIT: It has the list items but i want to show a value selected in the edit view...
public ActionResult Edit(int id)
{
var mesurementTypes = consRepository.FindAllMeasurements();
ViewData["MeasurementType"] = mesurementTypes;
var material = consRepository.GetMaterial(id);
return View("Edit", material);
}
My repository method,
public IEnumerable<SelectListItem> FindAllMeasurements()
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name
};
return mesurements;
}
Set the selected item when you create the IEnumerable<SelectListItem>.
Personally I would create a specialized viewmodel for the form but going by your code, do something like:
public ActionResult Edit(int id)
{
//Put this first
var material = consRepository.GetMaterial(id);
//pass in your selected item
var mesurementTypes = consRepository.FindAllMeasurements(material.MeasurementTypeId);
ViewData["MeasurementType"] = mesurementTypes;
return View("Edit", material);
}
Then change your repository method to something like:
public IEnumerable<SelectListItem> FindAllMeasurements(int selectedId)
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name,
Selected = mt.Id == selectedId
};
return mesurements;
}
HTHs,
Charles
Have a look at this blog entry.
http://weblogs.asp.net/ashicmahtab/archive/2009/03/27/asp-net-mvc-html-dropdownlist-and-selected-value.aspx
Basically, you need to convert your mesurementTypes list/enumerable into a SelectList or IEnumerable<SelectListItem>.
I would recommend, if possible, upgrading to ASP.NET MVC2 and using Html.DropDownListFor()
You should be returning a SelectionList which can specify a selected item.
How to create a DropDownList with ASP.NET MVC
Assuming that Model.Mes_Id contais the selected value, you can do something like this
<%
var Measurements = new SelectList((IEnumerable)ViewData["MeasurementType"], "Id", "Name", Model.Mes_Id);
Response.Write(Html.DropDownList("measurement_type", Measurements, "Select"));
%>
Html.DropDownListFor didn't work for me So I got the poppy like this
(in Edit method )
CreatList(long.Parse(wc.ParentID.ToString()));
private void CreatList(long selected= 0)
{
SqlConnection conn = new SqlConnection(Config.ConnectionStringSimple);
conn.Open();
Category wn = new Category(conn);
CategoryCollection coll = new CategoryCollection();
Category.FetchList(conn, ref coll);
ViewBag.ParentID = GetList(coll, selected);
}
private List<SelectListItem> GetList(CategoryCollection coll, long selected)
{
List<SelectListItem> st = new List<SelectListItem>();
foreach (var cat in coll)
{
st.Add( new SelectListItem
{
Text = cat.Name,
Value = cat.ID.ToString(),
Selected = cat.ID == selected
});
}
SelectListItem s = new SelectListItem {
Text = Resources.lblSelect,
Value = "0"
};
st.Insert(0, s);
return st;
}
<div class="editor-label">
#Html.LabelFor(model => model.ParentID)
</div>
<div class="editor-field">
#Html.DropDownList("ddlCat", (List<SelectListItem>)ViewBag.ParentID)
#Html.ValidationMessageFor(model => model.ParentID)
</div>

Resources