Reusable DropDownList Content - asp.net-mvc

I'm fairly new to ASP.NET MVC and am looking for help with the following issue.
I have a DropDownList control in a view. The selected value will be stored in an integer field of my model.
My preference is to not hard code the text and values in markup. In addition, I'd like to be able to use this same list of text and values in DropDownList controls in other views.
I'm not sure if I need to create a class that initializes these values somewhere, or perhaps I need an extension method. I could use some guidance on the best way to approach this.

This is a sample:
var apps = _webAppRepo.GetAll();
IList<SelectListItem> appSelectListItems = new List<SelectListItem>();
foreach (var item in apps) {
appSelectListItems.Add(new SelectListItem {
Text = item.ApplicationName,
Value = item.WebApplicationID.ToString()
});
}
ViewBag.AppSelectListItems = appSelectListItems;
And this is how you use it on you view:
#Html.DropDownListFor(model =>
model.WebApplicationID,
(IEnumerable<SelectListItem>)ViewBag.AppSelectListItems
)
If you would like to use it without a model, this is the way:
#Html.DropDownList("Foo",
(IEnumerable<SelectListItem>)ViewBag.AppSelectListItems
)

There are a number of ways of doing this, but you could do worse than storing these values in a view model, and rendering them on the page. I'm just using a Tuple here as an example:
public class MyViewModel
{
List<Tuple<int, string>> items_ = new List<Tuple<int, string>>();
public MyViewModel()
{
items_.Add(new Tuple<int, string>(1, "Item1"));
items_.Add(new Tuple<int, string>(2, "Item2"));
// etc
}
public List<Tuple<int, string>> Items { get { return items_; } }
}
Your controller:
public class MyController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
}
Your view:
#model MyNameSpace.MyViewModel
<select id="mySelect" name="mySelect>
#{foreach(Tuple<int, string> item in Model.Items){
<option value="#item.Item1">#item.Item2</option>
}}
</select>
Obviously, you can also make an extention method to create combo boxes in more interesting ways :)

You should populate your DropDownList from a database table, or from memory o reading from a xml file.
The you should be able to use the same data to populate any other ddl on your views.

Related

ASP.NET MVC - Dropdown - There is no ViewData item of type 'IEnumerable<SelectListItem>'

MenuType definiation:
public string Code { get; set; }
public string Name { get; set; }
ASP.NET MVC 5
I have searched and read before I'm posting my question here,
I'm trying to LOAD the data in the asp.net mvc dropdownlist why is that so complicated?
//controller
public class ClientController : BaseController
{
public ActionResult Index()
{
List<MenuType> ctypelist = db.ContractTypes.OrderBy(x => x.TypeOfContract).ToList();
IEnumerable<SelectListItem> list = new SelectList(ctypelist.ToList());
ViewBag.DropDownTypeOfContract = list;
return View();
}
}
//html
#model myapp.Models.Client
#Html.DropDownList("Codes", (List<SelectListItem>)ViewBag.DropDownTypeOfContract , new { style = "max-width: 600px;" })%>
What's complicated is that you can't seem to decide which type you're using...
First you have a List<MenuType> (I assume ContractTypes is actually of type MenuType?) Then you create a SelectList, passing the List<MenuType> to it, which implies that MenuType must have at least two properties, one called Text and one called Value. If not, you will have to specify the Text and Value property names in the SelectList constructor parameters.
After that, for some reason you convert it to a IEnumerable<SelectListItem>, then you assign that to a ViewBag item and call your View. So, at this point, your ViewBag.DropDownTypeOfContract is of type IEnumerable<SelectListItem>.
Next, in your View, you for some reason define an #model depite not passing any model at all to the view. Ok.... Whatever...
So now we get to the real problem.
#Html.DropDownList("Codes",
(List<SelectListItem>)ViewBag.DropDownTypeOfContract ,
new { style = "max-width: 600px;" })%>
Ok, let's ignore for a moment the fact that you have a WebForms closing code block indicator (%>) for some reason... The biggest problem here is that you're trying to cast ViewBag.DropDownTypeOfContract to a List<SelectListItem>, which is something it is not, and never was.
You converted the List<MenuType> to a SelectList which you then converted to an IEnumerable<SelectListItem>. There was never any List<SelectListItem> involved.
So, the simple fix (besides rewriting your code to be sane) is to change your cast as such:
#Html.DropDownList("Codes",
(IEnumerable<SelectListItem>)ViewBag.DropDownTypeOfContract,
new { style = "max-width: 600px;" })
EDIT:
Since your MenuType does not contain the appropriate properties, you will have to modify your SelectList as such (Which I mention above). FYI, ctypelist is already a list, no need to convert it to a list again... that's just silly.
IEnumerable<SelectListItem> list = new SelectList(ctypelist, "Code", "Name");
Note: I have posted this answer without knowledge of what variables your MenuType Class has. Please add to your question and I will edit this answer according to youe MenuType Class
All Dropdowns are a collection of Value and Text Pairs.
<select>
<option value=1>TEXT 1</option>
<option value=2>TEXT 2</option>
<option value=3>TEXT 3</option>
</select>
You have a list of List<MenuType>, Which values from the MenuType do you want to display in the DropDown List?
Assuming you have this as MenuType.cs
public class MenuType
{
public int MenuTypeId {get;set;}
public string Name {get;set;}
}
Your dropDown should be generated like this:
public ActionResult Index()
{
Dictionary<int,string> ctypelist = db.ContractTypes.OrderBy(x => x.TypeOfContract).ToDictionary(s => s.MenuTypeId, s=> s.Name);
IEnumerable<SelectListItem> selectListItems = ctypelist.Select(s => new SelectListItem() { Value = s.Key.ToString(), Text = s.Value });
ViewBag.DropDownTypeOfContract = selectListItems;
return View();
}
In View:
#{
var items = (IEnumerable<SelectListItem>) ViewBag.DropDownTypeOfContract;
}
#Html.DropDownList("Codes", items , "Select Item")

MVC: Best way to populate Html .DropDownList

I'm looking for a sound philosophy for bringing dynamic data into a view to populate a dropdownlist. Would it be a good idea to create a model object for dropdownlists and other "overhead" data or use a viewbag?
Thanks
Example for guidance:
I think the best way to achieve what you're after would be to use a ViewModel. You'd load the stuff you want to display in your View through this. So you'd create a dropdownlist with your accountlist which will be loaded in your controller. You'll also have your IEnumerable PErsoncontact in there which will also be loaded in your controller. Then your controller will pass the ViewModel to the View. You can use this as a guide.
ViewModel:
public class PersonViewModel
{
public int PersonID {get;set;}
public List<SelectListItem> PersonContactList {get;set;}
public IEnumerable<TypesAvail> TypesAvails{get;set;}
}
Dropdownlist in Razor View :
#Html.DropDownListFor(m => m.PersonID , Model.PersonContactList )
Edit:-
This is an example .Yes you can create a new class in same Model.
public class TypesAvail
{
public String TypeNme { get; set; }
public long TypeID { get; set; }
public int NumSelected { get; set; }
public int TypeCount { get; set; }
public IEnumerable<SelectListItem> CarsAvail
{
get
{
return new SelectList(
Enumerable.Range(0, TypeCount+1)
.OrderBy(typecount => typecount)
.Select(typecount => new SelectListItem
{
Value = typecount.ToString(),
Text = typecount.ToString()
}), "Value", "Text");
}
}
}
Dropdownlist in Razor View :
#Html.DropDownListFor(m=> m.NumSelected, Model.CarsAvail)
Using the ViewBag (as some have suggested in other answers/comments) to get data from your controller to view is generally seen as a code lack.
Your ViewModel should ideally contain all of the data you need for your view. So use your controller to populate this data on a property of your ViewModel:
Here is a simple example of how to create a drop down list in ASP.NET MVC using Html.DropDownListFor using model.
You can do it like this all inlined in your *.cshtml file like so:
#Html.DropDownListFor(model => model.Package.State, new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"}
},
"value",
"text",
2))
which will create like this:
<select id="Package_State" name="Package.State"><option value="0">Red</option>
<option value="1">Blue</option>
<option value="2">Green</option>
</select>
Refer to this answer for more information
Including the data in the View's Model or in the ViewBag are both good options, the best one depends entirely on your specific use case.
If this dropdown should be included on only one (or just a few) pages, it makes sense to be part of the ViewModel.
If every page should have the dropdown (if it's part of the menu, or footer for instance) you could create a BaseController that supplies ViewBag data for the dropdown, and let your other controllers inherit from that:
BaseController.cs
public class BaseController : Controller
{
public BaseController() {
ViewBag.MyDroprown = ...
}
}
Any other controller
// inheriting from BaseController will make ViewBag.MyDroprown accessible in the View
public class HomeController : BaseController
{
// Any actions here
}
In my opinion View model should contain all the data that is needed for rendering the view and that is available on view creation.
Using ViewBag for me is like using dynamic type in code - it gives you some flexibility but comes with the price of possible errors, so i try to avoid as much as possibe

Queries realted to Dropdown list in MVC

I am a new to ASP.NET MVC, I am developing an application. I want to bind the data in the drop down list in create view.
How to bind the data in the drop down? I have go through many question and answers here...
I have seen usually everyone suggested to use List<SelectListItem> what is its purpose?
Do I need to use ViewModel while binding the data to drop down list?
Can I get simple example where data get bind in the dropdown using viewbag?
I have created a list in controller
List<string> items = new List<string>();
and I want to pass this list to view using viewbag and simply want to bind to drop down list.
How to do this ?
I'd suggest using a ViewModel as it makes interaction with user input so much easier. Here's an example of how you might bind data from your ViewModel to a drop down in your View. First, the ViewModel:
public class CrowdViewModel
{
public string SelectedPerson { get; set;}
public IEnumerable<SelectListItem> People { get; set; }
}
So yes, you're right - use a collection of SelectListItems. I'm guessing in your case, the SelectListItem's Value and Text property will be the same. You could turn your List into IEnumerable like this:
[HttpGet]
public ActionResult Home()
{
// get your list of strings somehow
// ...
var viewModel = new CrowdViewModel
{
People = items.Select(x => new SelectListItem { Text = x, Value = x })
}
return View(viewModel);
}
Now you need to bind that ViewModel's property to the DropDown on your view. If you're using the Razor ViewEngine, the code will look something like this:
#model MyApp.ViewModels.CrowdViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.SelectedPerson, Model.People)
}
Now when you post that form, MVC will bind the selected value to the ViewModel's SelectedPerson property!
[HttpPost]
public ActionResult Home(CrowdViewModel viewModel)
{
// viewModel.SelectedPerson == whatever the user selected
// ...
}
Easy as that!
Update:
If you really want to use the ViewBag (don't do it), you can pass your list through from your Controller action like so:
[HttpGet]
public ActionResult Home()
{
ViewBag.People = new List<string> { "Bob", "Harry", "John" };
return View();
}
And then create a SelectList on your View:
#Html.DropDownList("SelectedPerson", new SelectList(ViewBag.People, Model))

Best practice for drop down boxes for web framework (ASP.NET MVC / ROR / Anything really)

I'm trying to work out a best practice for building drop down boxes for values that need to bind to values in a database.
Currently I am about to use the 3rd answer from this list How do you create a dropdownlist from an enum in ASP.NET MVC?
But then I was thinking if I bind strongly against the Enum, and then want to change the order of the items, or add new items, I'll need to make sure the order of the enum isn't actually the value being stored in the db, and have to have a binding layer of some kind.
Does anyone have the definitive way to work with drop down lists that relate to a db?
Personally I avoid using enums in my view models. They don't play well with ASP.NET MVC. So if I need to render a dropdown list in one of my views I define 2 properties on my corresponding view model:
public class MyViewModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
}
that are populated in my controller action from the database and in the view:
#Html.DropDownListFor(x => x.SelectedValue, Model.Values)
Have a strongly typed view model for the list with a partial view to match. Have an action in a controller which fills the view model and then returns it to the view. Wherever you want to use the dropdown, insert the partial view in your view.
I'm a fan of using an extension method for this task:
public static List<SelectListItem> ToSelectList<T>( this IEnumerable<T> enumerable, Func<T, string> value, Func<T, string> text, string defaultOption)
{
var items = enumerable.Select(f => new SelectListItem()
{
Text = text(f) ,
Value = value(f)
}).ToList();
if (!string.IsNullOrEmpty(defaultOption))
{
items.Insert(0, new SelectListItem()
{
Text = defaultOption,
Value = "-1"
});
}
return items;
}
Within your controller you select the data that you wan't to represent as items within a drop down. Note, in this example I'm selecting cities from the db:
SomeModel.City =
(from l in _locationRepository.GetAll() select new { l.Area.AreaDescription })
.Distinct()
.ToSelectList(x => x.AreaDescription, x => x.AreaDescription, "All");
And the actual drop down within the view:
#Html.DropDownList("City", Model.City)

ASP.NET MVC Html.DropDownList SelectedValue

I have tried this is RC1 and then upgraded to RC2 which did not resolve the issue.
// in my controller
ViewData["UserId"] = new SelectList(
users,
"UserId",
"DisplayName",
selectedUserId.Value); // this has a value
result: the SelectedValue property is set on the object
// in my view
<%=Html.DropDownList("UserId", (SelectList)ViewData["UserId"])%>
result: all expected options are rendered to the client, but the selected attribute is not set. The item in SelectedValue exists within the list, but the first item in the list is always defaulted to selected.
How should I be doing this?
Update
Thanks to John Feminella's reply I found out what the issue is. "UserId" is a property in the Model my View is strongly typed to. When Html.DropDownList("UserId" is changed to any other name but "UserId", the selected value is rendered correctly.
This results in the value not being bound to the model though.
This is how I fixed this problem:
I had the following:
Controller:
ViewData["DealerTypes"] = Helper.SetSelectedValue(listOfValues, selectedValue) ;
View
<%=Html.DropDownList("DealerTypes", ViewData["DealerTypes"] as SelectList)%>
Changed by the following:
View
<%=Html.DropDownList("DealerTypesDD", ViewData["DealerTypes"] as SelectList)%>
It appears that the DropDown must not have the same name has the ViewData name :S weird but it worked.
Try this:
public class Person {
public int Id { get; set; }
public string Name { get; set; }
}
And then:
var list = new[] {
new Person { Id = 1, Name = "Name1" },
new Person { Id = 2, Name = "Name2" },
new Person { Id = 3, Name = "Name3" }
};
var selectList = new SelectList(list, "Id", "Name", 2);
ViewData["People"] = selectList;
Html.DropDownList("PeopleClass", (SelectList)ViewData["People"])
With MVC RC2, I get:
<select id="PeopleClass" name="PeopleClass">
<option value="1">Name1</option>
<option selected="selected" value="2">Name2</option>
<option value="3">Name3</option>
</select>
You can still name the DropDown as "UserId" and still have model binding working correctly for you.
The only requirement for this to work is that the ViewData key that contains the SelectList does not have the same name as the Model property that you want to bind. In your specific case this would be:
// in my controller
ViewData["Users"] = new SelectList(
users,
"UserId",
"DisplayName",
selectedUserId.Value); // this has a value
// in my view
<%=Html.DropDownList("UserId", (SelectList)ViewData["Users"])%>
This will produce a select element that is named UserId, which has the same name as the UserId property in your model and therefore the model binder will set it with the value selected in the html's select element generated by the Html.DropDownList helper.
I'm not sure why that particular Html.DropDownList constructor won't select the value specified in the SelectList when you put the select list in the ViewData with a key equal to the property name. I suspect it has something to do with how the DropDownList helper is used in other scenarios, where the convention is that you do have a SelectList in the ViewData with the same name as the property in your model. This will work correctly:
// in my controller
ViewData["UserId"] = new SelectList(
users,
"UserId",
"DisplayName",
selectedUserId.Value); // this has a value
// in my view
<%=Html.DropDownList("UserId")%>
The code in the previous MVC 3 post does not work but it is a good start. I will fix it. I have tested this code and it works in MVC 3 Razor C# This code uses the ViewModel pattern to populate a property that returns a List<SelectListItem>.
The Model class
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
The ViewModel class
using System.Web.Mvc;
public class ProductListviewModel
{
public List<SelectListItem> Products { get; set; }
}
The Controller Method
public ViewResult List()
{
var productList = new List<SelectListItem>();
foreach (Product p in Products)
{
productList.Add(new SelectListItem
{
Value = p.ProductId.ToString(),
Text = "Product: " + p.Name + " " + p.Price.ToString(),
// To set the selected item use the following code
// Note: you should not set every item to selected
Selected = true
});
}
ProductListViewModel productListVM = new ProductListViewModeld();
productListVM.Products = productList;
return View(productListVM);
}
The view
#model MvcApp.ViewModels.ProductListViewModel
#using (Html.BeginForm())
{
#Html.DropDownList("Products", Model.Products)
}
The HTML output will be something like
<select id="Products" name="Products">
<option value="3">Product: Widget 10.00</option>
<option value="4">Product: Gadget 5.95</option>
</select>
depending on how you format the output. I hope this helps. The code does work.
If we don't think this is a bug the team should fix, at lease MSDN should improve the document. The confusing really comes from the poor document of this. In MSDN, it explains the parameters name as,
Type: System.String
The name of the form field to return.
This just means the final html it generates will use that parameter as the name of the select input. But, it actually means more than that.
I guess the designer assumes that user will use a view model to display the dropdownlist, also will use post back to the same view model. But in a lot cases, we don't really follow that assumption.
Use the example above,
public class Person {
public int Id { get; set; }
public string Name { get; set; }
}
If we follow the assumption,we should define a view model for this dropdownlist related view
public class PersonsSelectViewModel{
public string SelectedPersonId,
public List<SelectListItem> Persons;
}
Because when post back, only the selected value will post back, so it assume it should post back to the model's property SelectedPersonId, which means Html.DropDownList's first parameter name should be 'SelectedPersonId'. So, the designer thinks that when display the model view in the view, the model's property SelectedPersonId should hold the default value of that dropdown list. Even thought your List<SelectListItem> Persons already set the Selected flag to indicate which one is selected/default, the tml.DropDownList will actually ignore that and rebuild it's own IEnumerable<SelectListItem> and set the default/selected item based on the name.
Here is the code from asp.net mvc
private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata,
string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool allowMultiple,
IDictionary<string, object> htmlAttributes)
{
...
bool usedViewData = false;
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = htmlHelper.GetSelectData(name);
usedViewData = true;
}
object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string));
// If we haven't already used ViewData to get the entire list of items then we need to
// use the ViewData-supplied value before using the parameter-supplied value.
if (defaultValue == null && !String.IsNullOrEmpty(name))
{
if (!usedViewData)
{
defaultValue = htmlHelper.ViewData.Eval(name);
}
else if (metadata != null)
{
defaultValue = metadata.Model;
}
}
if (defaultValue != null)
{
selectList = GetSelectListWithDefaultValue(selectList, defaultValue, allowMultiple);
}
...
return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
}
So, the code actually went further, it not only try to look up the name in the model, but also in the viewdata, as soon as it finds one, it will rebuild the selectList and ignore your original Selected.
The problem is, in a lot of cases, we don't really use it that way. we just want to throw in a selectList with one/multiple item(s) Selected set true.
Of course the solution is simple, use a name that not in the model nor in the viewdata. When it can not find a match, it will use the original selectList and the original Selected will take affect.
But i still think mvc should improve it by add one more condition
if ((defaultValue != null) && (!selectList.Any(i=>i.Selected)))
{
selectList = GetSelectListWithDefaultValue(selectList, defaultValue, allowMultiple);
}
Because, if the original selectList has already had one Selected, why would you ignore that?
Just my thoughts.
This appears to be a bug in the SelectExtensions class as it will only check the ViewData rather than the model for the selected item. So the trick is to copy the selected item from the model into the ViewData collection under the name of the property.
This is taken from the answer I gave on the MVC forums, I also have a more complete answer in a blog post that uses Kazi's DropDownList attribute...
Given a model
public class ArticleType
{
public Guid Id { get; set; }
public string Description { get; set; }
}
public class Article
{
public Guid Id { get; set; }
public string Name { get; set; }
public ArticleType { get; set; }
}
and a basic view model of
public class ArticleModel
{
public Guid Id { get; set; }
public string Name { get; set; }
[UIHint("DropDownList")]
public Guid ArticleType { get; set; }
}
Then we write a DropDownList editor template as follows..
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<script runat="server">
IEnumerable<SelectListItem> GetSelectList()
{
var metaData = ViewData.ModelMetadata;
if (metaData == null)
{
return null;
}
var selected = Model is SelectListItem ? ((SelectListItem) Model).Value : Model.ToString();
ViewData[metaData.PropertyName] = selected;
var key = metaData.PropertyName + "List";
return (IEnumerable<SelectListItem>)ViewData[key];
}
</script>
<%= Html.DropDownList(null, GetSelectList()) %>
This will also work if you change ArticleType in the view model to a SelectListItem, though you do have to implement a type converter as per Kazi's blog and register it to force the binder to treat this as a simple type.
In your controller we then have...
public ArticleController
{
...
public ActionResult Edit(int id)
{
var entity = repository.FindOne<Article>(id);
var model = builder.Convert<ArticleModel>(entity);
var types = repository.FindAll<ArticleTypes>();
ViewData["ArticleTypeList"] = builder.Convert<SelectListItem>(types);
return VIew(model);
}
...
}
The problems is that dropboxes don't work the same as listboxes, at least the way ASP.NET MVC2 design expects: A dropbox allows only zero or one values, as listboxes can have a multiple value selection. So, being strict with HTML, that value shouldn't be in the option list as "selected" flag, but in the input itself.
See the following example:
<select id="combo" name="combo" value="id2">
<option value="id1">This is option 1</option>
<option value="id2" selected="selected">This is option 2</option>
<option value="id3">This is option 3</option>
</select>
<select id="listbox" name="listbox" multiple>
<option value="id1">This is option 1</option>
<option value="id2" selected="selected">This is option 2</option>
<option value="id3">This is option 3</option>
</select>
The combo has the option selected, but also has its value attribute set. So, if you want ASP.NET MVC2 to render a dropbox and also have a specific value selected (i.e., default values, etc.), you should give it a value in the rendering, like this:
// in my view
<%=Html.DropDownList("UserId", selectListItems /* (SelectList)ViewData["UserId"]*/, new { #Value = selectedUser.Id } /* Your selected value as an additional HTML attribute */)%>
In ASP.NET MVC 3 you can simply add your list to ViewData...
var options = new List<SelectListItem>();
options.Add(new SelectListItem { Value = "1", Text = "1" });
options.Add(new SelectListItem { Value = "2", Text = "2" });
options.Add(new SelectListItem { Value = "3", Text = "3", Selected = true });
ViewData["options"] = options;
...and then reference it by name in your razor view...
#Html.DropDownList("options")
You don't have to manually "use" the list in the DropDownList call. Doing it this way correctly set the selected value for me too.
Disclaimer:
Haven't tried this with the web forms view engine, but it should work too.
I haven't tested this in the v1 and v2, but it might work.
I managed to get the desired result, but with a slightly different approach. In the Dropdownlist i used the Model and then referenced it. Not sure if this was what you were looking for.
#Html.DropDownList("Example", new SelectList(Model.FeeStructures, "Id", "NameOfFeeStructure", Model.Matters.FeeStructures))
Model.Matters.FeeStructures in above is my id, which could be your value of the item that should be selected.

Resources