I am merely trying to get items into an Html.DropDownList() as follows. I've debugged and know the data is coming across to the View but the dropdownlist is not displayed. Anyone know where I'm going wrong here?
#model List<ControlNumberViewer.Models.Table>
#{
Layout = null;
}
Control Number Viewer
<div id="PickTable">
#{Html.DropDownList("TableName", Model.Select(x => new SelectListItem
{
Text = x.TableName,
Value = x.TableName
}));
}
</div>
Pull your data into the controller and store it in a ViewBag. Then use DropDownListFor for strongly typed access to the data for the property TableName.
in your controller:
var linqQuery = _db.SQLTable.Select(x => new { Text = x.TableName, Value = x.TableName });
ViewBag.ListValues = new SelectList(linqQuery, "Value", "Text");
in your view:
#Html.DropDownListFor(m => m.TableName, ViewBag.ListValues as SelectList);
#{
var listitem = Model.Select(x => new SelectListItem {
Text = x.TableName,
Value = x.TableName
});
Html.DropDownList("TableName", (SelectList)listitem);
}
Related
I have a DropDownListFor that takes data source from controller. Is there a way to update it since i'm adding new values that i want then to be displayed on the same page.
View:
#Html.DropDownListFor(m => m.Id, MyController.GetIds(Model.Id).Select(g => new SelectListItem { Text = g.Text, Value = g.Value }), #Resource.System_Choose, new
{
#class = "form-control selectpicker",
data_live_search = "true"
})
Controller:
public static List<SelectListItem> GetIds(int Id)
{
var retVal = new List<SelectListItem>();
return retVal;
}
Make your View deal with Model that has property of type List<SelectListItem>() and return this property ready to be binded and displayed in DropDown.
There are some ways to achieve the goal,
Use only javascript to append the new value to select options. (If the new value doesn't send to backend)
Ajax and get the new list.
A sample for case 2, we can put the DropDownList to a partialview and use ajax to get the latest DropDownList in the partialview.
Controller :
public ActionResult QueryNewList()
{
return PartialView("~/Views/Home/_urPartialView.cshtml", viewModel);
}
Html:
<div id="myDiv"></div>
Js:
$.ajax({
dataType: "html",
url: "QueryNewList",
success: function (html) {
$("#myDiv").html("");
$("#myDiv").append(html);
}
})
I have an ASP.NET MVC 4 app. I'm not an MVC expert. In my view (.cshtml file), I have a Model that I'm binding to. In my model, I have a list of short values setup like this:
public void Load() {
List<short> options = new List<short>();
options.Add(1);
options.Add(3);
options.Add(7);
this.Options = options;
}
public List<short> Options = new List<short>() { get; set; }
public short? SelectedOption = null;
In my .cshtml file, I need to let the user choose one of the options from a drop down list. I see a bunch of HTML helpers, but I'm totally confused how to do this. How do I just display the drop down list and bind it back to my model? I am successfully binding to text boxes already, so I know I have my plumbing setup correctly. Its just this drop down list that's throwing me for a loop.
Thank you!
Suppose the object you are passing to the .cshtml view is your list which can be either passed through the ViewBag or as model.
Then depending in your requirement you can use multiple things to make a dropdown list out of which most preferable would be.
Html.DropDownList extention. Link to MSDN
so typical code would be
var options = Model ; //OR Viewbag.Options;
#Html.DropDownList(options.Select(o=>
new SelectListItem()
{
Text = o.ToString(),
Value = o.ToString()}
))
Also if you want to do it without any such specialized helper then
you can just create the HTML yourself.
<select>
#foreach(var o in Options){
<option value="#o.ToString()">#o.ToString()</option>
}
</select>
Small working snippet:
#model SelectListItem
#{
ViewBag.Title = "Index";
Layout = null;
List<SelectListItem> x = new List<SelectListItem>()
{
new SelectListItem { Text = "1", Value = "100", Selected = false },
new SelectListItem { Text = "2", Value = "200", Selected = true }
};
}
<html>
<head>
<title></title>
<script src="~/Scripts/jquery-1.8.2.js"></script>
</head>
<body>
#Html.DropDownListFor(model => model.Text, x)
</body>
</html>
<h2>Index</h2>
Above is the code of a view. You can pass a full model from the controller, when calling the View method, that will contain the list of elements you want to show. For the example, I simply created it on the fly (x list)
You can use this way for a dropdownlist..
In your controller
var sample = new List<SelectListItem> { new SelectListItem { Text = "--Select--", Value = "0" }, new SelectListItem { Text = "A", Value = "1" }, new SelectListItem { Text = "B", Value = "2" } };
ViewBag.something = sample;
In your View,
#Html.DropDownListFor(m => m.colname, (List<SelectListItem>)ViewBag.something , null, new { type = "text", Class = "", style = "" })
I am using DropDownListFor to render a dropdown list in a view. Somehow the rendered list does not select the SelectListItem with Selected set to true.
In the controller action:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Selected = entry.Value.Equals(selectedValue),
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = id,
SelectList = selectList,
OptionLabel = "Click to Select"
});
In the view:
<%= Html.DropDownListFor(m => m.ListId,
Model.SelectList,
Model.OptionLabel,
new {#class="someClass"}) %>
I have tried the following:
make sure that there is one and only one items with Selected set to true.
remove the option label argument.
remove the HTML attribute object.
use SelectList in DropDownListFor:
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {#class="someClass"})
Any suggestions as to what went wrong?
EDIT:
more information:
This action is a child action, called by another view with HTML.RenderAction
DropDownListFor will always select the value that the listbox is for, so in this case it will look at the value of ListId and make that item in the list selected. If ListId is not found in the list, the first item (or default text) will be selected. If you want a list that selects based on the selected attribute use DropDownList (without the For, in that case you have to name it yourself).
So in your case this would work:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
I got the same problem on the same model (with the other models in the decision no problem)
Does not work:
#Html.DropDownListFor(o => o.Drivers.ValueListItems.Value, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
Works perfectly, the elements selected:
#Html.DropDownListFor(o => o.Drivers.ValueListItems.ToDictionary(u=>u.Value).Values, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
Try like this:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
// The drop down list is bound to ListId so simply set its value
// to some element value in the list and it will get automatically
// preselected
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
and in the view:
<%= Html.DropDownListFor(
m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text"),
Model.OptionLabel,
new { #class = "someClass" }
) %>
There could be one more gotcha: you are trying to change the selected value in a POST action. For example you rendered a form, the user selected some value in the dropdown, submitted the form and in your POST action you do some processing on this selected value and when you redisplay the view you want the drop down list to have some other value selected. In this case you will have to remove the initial selection which is contained in the ModelState or the Html helper will ignore the selected value in the model:
// do this before returning the view and only if your scenario
// corresponds to what I described above
ModelState.Remove("ListId");
The solution for this problem is simpler that we all think...
All we need to do is set the property on the view model for the element that the dropdown is bound to - i.e: ListId = 3 for example
this way when we do this
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {#class="someClass"})
the HtmlHelper will automatically pick up the default value to display on the DropDownList
simples!
Hope it may help you and all the others - like me! - that have lost a lot of time searching for a solution for this apparent issue.
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") %>
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"))