ASP.Net MVC Add Items To Bound Dropdownlist - c#

My page view currently has a dropdownlist on it that is getting bound to a collection from the controller. This is working fine, However I want to insert an item to the top of the dropdownlist that is not in my collection e.g the list currently gets the following items
Open
Closed
I want to add a third option of "All" but I don't want to add this option to my database. In Webforms I would have just bound the control then inserted another item however it seems this is not possible with MVC, am I right in thinking I will need to add some Javascript to the view to add this new item once the dropdownlist has been bound?
Thanks

No. Construct your data as a list of SelectListItems and prepend in the controller.
var list = db.Table
.Select( t => new SelectListItem
{
Key = t.ID.ToString(),
Value = t.Name
} )
.ToList();
list.Insert( 0, new SelectListItem { Key = "-1", Value = "All" } );
ViewData["TableSelect"] = list;
On the view side:
<%= Html.DropDownList( "TableID",
(IEnumerable<SelectListItem>)ViewData["TableSelect"] ) %>

Simple
you can make it as you wish in controller.
and pass it in viewdata.
other option is directly in view page.
<%= Html.DropDownList("DropDown","all" )%>
But you can add only one option..
Make sure you are not storing added options in ur db, right?
so before you save it, check option value in action and apply your logic.

Newer implementation
var list = _db.Status.ToList();
list.Add(new Status(){DevelopmentStatusID = -1, DevelopmentStatusDesc = "All"});
var result = list.OrderBy(d => d.StatusID).ToList();
ViewBag.StatusID = new SelectList(result, "StatusID", "StatusDesc");
Then in the index.html
#Html.DropDownList("StatusID", null, htmlAttributes: new {#class = "form-control"})

Related

Get selected item of DropDownListFor and using it to create new list

Have some problems trying to solve this. Have two DropDownListFor where the first is populated with data and the second should be populated using the selected value from the first.
Lets say the first DropDownlist contains these data:
RoutesList;
Value = "CoOs", Text = "Copenhagen - Oslo",
Value = "StOs", Text = "Stockholm - Oslo",
Value = "OsCo", Text = "Oslo - Copenhagen"
In my razor view I'm trying to create a new list based on the selected value.
How do I get the selected value, lets say "StOs" and format it so it only contains the first two letters "St"? Trying to do this with C# and not Jquery.
My code
// Loads RoutesList to departureRouteSelectList
var departureRouteSelectList = Model.RoutesList;
// Finds selected value
var selectedItem = departureRouteSelectList.Select(x => x.Value);
// Create new selectList for returnRoute
List<SelectListItem> returnRouteSelectList = null;
I'm not sure if the "Select" command does what I want and getting the "StOs"?
Understanding what you want make me think this post will resolve your problem:
Can't get my DropDownListFor to select a selected SelectListItem item in a Dropdown menu

Multiple default selected items in Listbox

I'm looking into creating an Edit page for a Company object that has multiple categories (that are predefined in a list). I have the list being sent through the ViewBag, and have the categories that the user selected in the Create page in an Array thanks to a ViewModel.
I can't figure out a way to have the ListBox prepopulate with the multiple values in my array. I was playing around with jQuery and was able to get one of the values to be selected, but when I try more than one nothing shows up. Any ideas?
#Html.ListBox("Category", new SelectList(ViewBag.Category, "Text", "Value"))
The SelectListItem object has a Selected property to indicate this. So I guess it would come down to how you build the SelectList. Currently you do this:
new SelectList(ViewBag.Category, "Text", "Value")
Which works, but gives you no control over the individual SelectListItems. Instead of building a SelectList, you can build an IEnumerable<SelectListItem> using the same method overload. Initially that might look like this:
ViewBag.Category.Select(c => new SelectListItem
{
Text = c.Text,
Value = c.Value
});
At this point you have more control over the individual items. Now it's just a matter of determining which ones should be selected. How do you determine that? Is it a property on the Category object? Something like this?:
ViewBag.Category.Select(c => new SelectListItem
{
Text = c.Text,
Value = c.Value,
Selected = c.Selected
});
Or perhaps some other condition?:
ViewBag.Category.Select(c => new SelectListItem
{
Text = c.Text,
Value = c.Value,
Selected = c.SomeValue == SomeCondition
});
How you determine that is up to you, and ideally something you can logically add to the backing model being used here.

Setting the Selected Value of a Dropdown list in the View from the Controller Action

I have 5 dropdowns, which are basically displaying "Select", "Yes" and "No". Initially they are set to "Select". Once he user chooses something, I am storing the data in a cookie (with Jquery) and eventually passing this to the ViewModel so that I can use it in the Controller.
When the user refreshes the page, I want these dropdown lists to be populated again with the value I have in the ViewModel.
At the moment I have the following code :-
Inside the View I have
<%: Html.DropDownList("FirstQuestYesNo", ViewData["FirstQuestYesNoData"] as SelectList, new { #class = "normalDropdowns" })%>
and in my controller I have the following :-
var ddlYesNoData = new SelectList(new[]
{
new {ID="",Name=#Resources.GeneralTerms.GeneralTerms_Select},
new {ID="Yes",Name=#Resources.GeneralTerms.GeneralTerms_Yes},
new{ID="No",Name=#Resources.GeneralTerms.GeneralTerms_No},
},
"ID", "Name", 1);
//Refresh the YesNo dropdown with the correct vals
Dictionary<string, string> YesNoData = new Dictionary<string, string>();
YesNoData.Add("FirstQuestYesNoData", viewModel.FirstQuestYesNoValue);
YesNoData.Add("SecondQuestYesNoData", viewModel.SecondQuestYesNoValue);
YesNoData.Add("ThirdQuestYesNoData", viewModel.ThirdQuestYesNoValue);
YesNoData.Add("FourthQuestYesNoData", viewModel.FourthQuestYesNoValue);
YesNoData.Add("FifthQuestYesNoData", viewModel.FifthQuestYesNoValue);
foreach (var item in YesNoData)
{
ViewData[item.Key] = ddlYesNoData;
if (item.Value != null)
{
var selected = ddlYesNoData.Where(x => x.Value == item.Value).First();
selected.Selected = true;
}
}
So basically what I am doing is get the value of each dropdown from the viewModel, and then try to set that value inside my View. As a result of what I am doing, I am getting all the DropdownLists option as "Select" instead of the value inside my viewModel.
The problem is that I do not know how to "target" the specific DropDownList. How can I target the DropDown (in this case "FirstQuestYesNo") from the Controller using my code?
Thanks for your help and time.
In your controller action simply set the FirstQuestYesNo property to the corresponding value. For example:
ViewData["FirstQuestYesNo"] = "Yes"; // this value might come from a cookie
This will automatically preselect the option with value="Yes". Obviously this value will come from the cookie. You don't need any foreach loops.

Why does this render as a list of "System.Web.Mvc.SelectListItem"s?

I'm trying to populate a DropDownList with values pulled from a property, and my end result right now is a list of nothing but "System.Web.Mvc.SelectListItem"s. I'm sure there's some minor step I'm omitting here, but for the life of me I can't figure out what it is.
The property GET generating the list:
public IEnumerable<SelectListItem> AllFoo {
get {
var foo = from g in Bar
orderby g.name
select new SelectListItem {
Value = g.fooid.ToString(),
Text = g.name
};
return foo.AsEnumerable();
}
}
The controller code:
public ActionResult Edit(string id) {
// n/a code
ViewData["fooList"] = new SelectList(g.AllFoo, g.fooid);
return View(g);
}
The view code:
<%= Html.DropDownListFor(model => model.fooid, ViewData["fooList"] as SelectList) %>
The problem here is that you shoudn't fill a SelectList with an IEnumerable<SelectListItem>. Use either SelectList or an IEnumerable<SelectListItem>, but not both. For more details, have a look at this question: Asp.Net MVC 2 Dropdown Displaying System.Web.MVC.SelectListItem
I ran into the same problem. You should render your List in the view like
#Html.DropDownListFor(model => model.fooid, new
SelectList(ViewData["fooList"],"Text","Value", Model.DefaultValue))
This is based on c# with razor view
EDIT: This question is very similar to one that was already asked:
ASP.NET MVC 2 - Html.DropDownListFor confusion with ViewModel
Otherwise, you might find this article helpful:
http://www.nickriggs.com/posts/rendering-and-binding-drop-down-lists-using-asp-net-mvc-2-editorfor/
It uses EditorFor, but the same can be done for DisplayFor.

SelectedItem not being remembered in SelectList in ASPNET.MVC

I have the following code which is meant to populate a dropdown with a bunch of integer values and make the currently selected value (in this case, 13) be the selected item.
I've used the same technique but for string values and it works great, remembering each time when I get to the view what the current value is.
In controller:
var x = new[] { 1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
ViewData["Field"] = new SelectList(x, 13);
In view:
<%=Html.DropDownList("Field", (IEnumerable<SelectListItem>)ViewData["Field"])%>
When I debug and watch the ViewData["Field"] object, it does have a selectedValue of 13 and so it must be reaching the View but getting ignored there as all I see on the page is a dropdown with the values 1 to 15, but with 1 showing (none selected so shows the first one)
Is this a bug or am I doing something really stupid?
Thanks
Graeme
I seem to recall that it doesn't actually use the Selected property of the SelectList element. I usually have one ViewData item be the select list and another be the selected value.
Controller:
var x = new[] { 1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
ViewData["Fields"] = new SelectList(x);
ViewData["Field"] = 13;
View
<%= Html.DropDownList("Field", (IEnumerable<SelectListItem>)ViewData["Fields"] ) %>
This was happening to me! I was pulling my hair out for hours, but I eventually figured it out. In my case I was creating a drop-down list like this:
<%= Html.DropDownList("bookId", Model.ProductMenu, new { onchange = "goToBook();" })%>
And it was not printing the selected option. But the dropdown right next to it was working fine:
<%= Html.DropDownList("segmentIndex", Model.SegmentMenu, new { onchange = "goToSegment();" })%>
They were being generated the exact same way in the controller, and the debugger would always show the properly selected value as the view was returned. So what the heck?
The difference was in the view itself. "bookId" in my app happens to be a route/querystring value and segmentIndex is not. Simply changing the name "bookId" in the view to "bookIdBLAH" fixed it!

Categories

Resources