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...
Related
I was wondering if there was a way to pass more than 1 list to a view to render.
Here is my code in PeopleController
public ActionResult Index()
{
EmployeeContext db = new EmployeeContext();
//Sites
List<SelectListItem> listSelectListItem = new List<SelectListItem>();
foreach (Sites loc in db.Locations)
{
SelectListItem selectListItem = new SelectListItem()
{
Text = loc.HRSite,
Value = loc.HRSite
};
listSelectListItem.Add(selectListItem);
}
SiteViewModel siteViewModel = new SiteViewModel();
siteViewModel.Sites = listSelectListItem;
//Cost Centers
List<SelectListItem> listSelectListItem2 = new List<SelectListItem>();
foreach (CostCenter cc in db.CostCenterNumbers)
{
SelectListItem selectListItem = new SelectListItem()
{
Text = cc.CostCenterNumber,
Value = cc.CostCenterNumber
};
listSelectListItem2.Add(selectListItem);
}
CCViewModel ccViewModel = new CCViewModel();
ccViewModel.CostCenter = listSelectListItem2;
List<object> myModel = new List<object>();
myModel.Add(siteViewModel);
myModel.Add(ccViewModel);
return View(myModel);
Here is my View:
#model IEnumerable<object>
#{
List<MVCDemo.Models.CostCenter> lstCostCenter = Model.ToList()[0] as List<MVCDemo.Models.CostCenter>;
List<MVCDemo.Models.Sites> lstLocation = Model.ToList()[1] as List<MVCDemo.Models.Sites>;
}
<h3>Cost Center</h3>
<ul>
#foreach (var item in lstCostCenter)
{
<li>#item.CostCenterNumber</li>
}
</ul>
<hr />
<h3>Site</h3>
<ul>
#foreach (var item in lstLocation)
{
<li>#item.HRSite</li>
}
</ul>
How can I change the view to contain 2 listboxes instead of 2 "lists"?
Create a concrete view containing a collection for each of your lists.
Then for each of your collections use
#Html.ListboxFor(m => m.YourCollection)
More info: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.listboxfor(v=vs.118).aspx
I suggest creating a ViewModel to hold your data. It is far more convenient that simply passing "object" around. There are many benefits of it and one would be that you could use the strongly typed html helpers in razor.
Then you can use the #Html.ListboxFor as suggested by dan m
I'm not currently happy with the way that my DropDownListFor() objects are populated. I'm attempting to find as generic way of populating IEnumerable as possible. This is what I have so far.
Helper:
public static List<SelectListItem> ToSelectList(IDictionary<string,string> dictionaryItems, string selectedValue, string noSelection, bool search = false)
{
List<SelectListItem> items = new List<SelectListItem>();
if (search)
{
items.Add(new SelectListItem { Selected = true, Value = "-1", Text = string.Format("-- {0} --", noSelection) });
}
foreach (var item in dictionaryItems)
{
items.Add(new SelectListItem
{
Text = item.Key,
Value = item.Value,
Selected = selectedValue == item.Value ? true : false
});
}
return items
.OrderBy(l => l.Text)
.ToList();
}
Controller:
[HttpGet]
public ActionResult Index()
{
var model = new CreateModel();
var parentOrganisations = _orgs.FindBy(o => o.OwningOrganisationID == Globals.OrganisationID || o.ID == Globals.OrganisationID)
.OrderBy(o => o.OrganisationName);
Dictionary<string, string> items = new Dictionary<string, string>();
foreach (var item in parentOrganisations)
{
items.Add(item.OrganisationName, item.ID.ToString());
}
model.Organisations = SelectLists.ToSelectList(items, "-1", "-- None -- ", true);
return View(model);
}
View:
<div class="control-group">
<label class="control-label">Parent Organisation</label>
<div class="controls">
#Html.DropDownListFor(m => m.ParentOrganisationID, Model.Organisations, new { #class = "input-xlarge"})
<p class="help-block">Select a parent organisation to create a branch</p>
</div>
</div>
There seems to be A LOT of repetitive code in the controller. It takes a generic list, add's the Value and Text to a Dictionary and then uses that as input for a helper which builds up the select list to send as part of the model.
Does anyone have any better ways to achieve this? I hate having bloat in my controller, and when I get several drop downs on a form this is exactly what will happen in this instance.
Thanks,
EDIT - Thanks to Kenneth's helper method, I've now consolidated the whole thing into one call in the controller:
model.Organisations = _orgs.FindBy(o => o.OwningOrganisationID == Globals.OrganisationID || o.ID == Globals.OrganisationID)
.OrderBy(o => o.OrganisationName)
.ToList()
.ToSelectList(org => org.OrganisationName, org => org.ID.ToString(), "-1", "None", true);
You could provide callbacks that obtain the key and the value and then use those. Apart from that you can create it as an extension method:
Extension method:
public static List<SelectListItem> ToSelectList<T>(this List<T> Items, Func<T, string> getKey, Func<T, string> getValue, string selectedValue, string noSelection, bool search = false)
{
List<SelectListItem> items = new List<SelectListItem>();
if (search)
{
items.Add(new SelectListItem { Selected = true, Value = "-1", Text = string.Format("-- {0} --", noSelection) });
}
foreach (var item in Items)
{
items.Add(new SelectListItem
{
Text = getKey(item),
Value = getValue(item),
Selected = selectedValue == getValue(item) ? true : false
});
}
return items
.OrderBy(l => l.Text)
.ToList();
}
Usage:
List<Org>() parentOrganisations = // fetch here
model.Organisations = parentOrganisations.ToSelectList(org => org.ID.ToString(),
org => org.OrganisationName,
"-1",
"-- None -- ",
true);
Note: I typed this in the SO-editor, so you might have some syntax errors (they should be easy to solve though).
You can do in controller only like this: -
List<SelectListItem> dropdownItems = parentOrganisations
.Select(item => new SelectListItem
{
Value = item.ID.ToString(),
Text = item.OrganisationName,
Selected = "-1" == item.ID.ToString() ? true : false
})
.ToList();
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") %>
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>
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"))