asp.net mvc dropdownlist no ViewData item - asp.net-mvc

i start to study mvc, try to add dropdownlist, make construction
<%= Html.DropDownList("ddl") %>
but it show error
There is no ViewData item of type 'IEnumerable' that has the key 'ddl'
why? i use simple code, only pass name parameter, so why the error?

Actually Html.DropDownList is an HTML helper that create html select element. When you pass ddl as argument it expects to get an array or list or something like that (an object implementing IEnumerable interface) to populate the dropdownlist. try it like this:
In Controller:
ViewData["ddl"]=new string[]{'Jan', 'Feb','Mar','Apr'.......'Dec'};
then it will create a select element containing the given values. For more information read this article.

"There is no ViewData item of type 'IEnumerable'"
It means that helper method is expecting an item of type 'IEnumerable' for e.g, List<> with an Id 'ddl'
If you are trying to display a DropDownList which has items from some static source, here is one way to do this.
// create new IEnummerable
List<string> ddl =
new List<string>(new [] {"item1","item2" };
// add Items
ddl.Add("Item1");
ddl.Add("Item2");
// return View which holds ddl now
ViewData["ddl "] = ddl ;
return View();
For more insight have a look at
Understanding HTML Helpers
How to create a DropDownList with
ASP.NET MVC

Here is an example of adding a DropDownList in ASP.NET-MVC. You need to provide an item of type 'IEnumerable' with a key 'dll' in the ViewData, as the error says.

Related

Populating a dropdown from ViewData

I have viewdata in my controller which is populated by a list:
List<employee> tempEmpList = new List<employee>();
tempEmpList = context.employees.ToList();
ViewData["tempEmpList"] = tempEmpList;
and I am passing this into my view, the question is, how do I place the content of the viewdata list into a dropdown list?
The display data will be .name from the list item.
I know I could do a foreach on the Viewdata and create a select list, but this seems a bit long winded
You can use the DropDownList html helper:
#Html.DropDownList("SelectedEmployee",
new SelectList((IEnumerable) ViewData["tempEmpList"]), "Id", "Name")
In the SelectList constructor, you can specify which properties of the Employee class should be used as both the text and the value within the dropdown (e.g. "Id", "Name")
The name of the dropdown ("SelectedEmployee") will be used when you post back your data to the server.
Set up your ViewData in the normal way, assigning a Key name that maps to a property in your model that will be bound on Post ...
ViewData["ModelPropertyName"] = new SelectList(...)
Then in your view simply add a Html.DropDownList ...
#Html.DropDownList("ModelPropertyName")
Please try with that. I have tried with MVC5
#Html.DropDownList("SelectedEmployee", new SelectList((System.Collections.IEnumerable) ViewData["tempEmpList"],"id","Name"))

Issue with Html.EditorFor on MVC3

I have a view with a form that's is typed to a viewmodel called AddEditItemVM. This viewmodel has the following property:
public List<Category> Categories{get;set;}
What im trying is two things:
Render a checkbox foreach Category in the generic category list of my viewmodel.
Make that when the form is posted receive, in my controller action, the property Categories instantiated (into the instance of AddEditItemVM)
About the first point, i would like to use any helper (if exists) that renders a group of checkboxes using lambda expressions like (m=>m.Categories), instead to render the checkbox with a foreach into the view.
About the second point, i read that there is one feature in MVC called Custom Model Binders. These get values from ValueProviders (querystring, cookies, or Form values) and creates the necessary instances passing it to specific action called after a form was posted. Should i create one custom model binder in order to receive my property Categories instantiated?
This might work
CheckboxList in MVC3.0

ASP.Net MVC, Dynamic Property and EditorFor/LabelFor

I am using MVC 3 w/ Razor and using the new dynamic ViewBag property. I would like to use the ViewBag property with the EditorFor/LabelFor Html helpers but can't figure out the syntax.
The View does have a #model set, but the object I am trying to use is not part of that model. I am aware I can create a ViewModel but that is not what I am after.
Can anyone help?
Controller:
var myModel= _repo.GetModel(id);
var newComment = new Comment();
ViewBag.NewComment = newComment;
return View(myModel);
View:
#model Models.MyModel
#(Html.EditorFor(ViewBag.NewComment.Comment))
I haven't tried it, but this should work I think.
#(EditorFor(m => ViewBag.NewComment)
It is possible to use a Linq-to-SQL syntax, but use a completely different object on the right side.
Not knowing what your Comment Model looks like, my gut reaction would be to just do:
#Html.EditorFor(ViewBag.NewComment)
However, because ViewBag is dynamic, you may need to cast NewComment before you use it, in order to get the EditorFor magic.
#Html.EditorFor(ViewBag.NewComment as Comment)
Update
Strike that, EditorFor can only accept an Expression as a parameter, and that Expression must return a property of the page model. I don't think EditorFor or EditorForModel are going to be of any use to you if you don't want to use a ViewModel. Have you considered switching the roles of whatever it is you're using the Model for, with that of the ViewBag?
If for some reason I need to use ViewData to pass the model into my view I do the following to allow for the Html.DisplayFor() helpers.
In the views code block I cast the ViewData model object to its underlying type
var newCommentModel = ( NewComment )ViewBag.NewComment;
Then I assign the following expression to the helper using the strong-typed reference
#Html.DisplayFor( model => newCommentModel )
The expression tree now contains a strongly-typed model and the DisplayTemplate is correctly displayed.

ASP.NET MVC SelectList: How do I set class name and other attributes?

How can I set a select class and other attributes eg:events through the SelectList object?
If this cannot be done, what are the best practices in populating a select input (dropdownlist) ie should I just loop through the items and render the <option> tags
I guess events should be bound to the controls in jquery for instance, but I do need the class forto do this.
The htmlAttributes parameter should take an anonymous type initialised like this :
new {#class="some-css-class"}
<%=Html.DropDownList("elementname",yourSelectList,"defaultvalue",new{#class="yourclass"}) %>

Add empty value to a DropDownList in ASP.net MVC

I'm building a data entry interface and have successfully bound the columns that have reference tables for their data using DropDownList so the user selects from the pre-configured values.
My problem now is that I don't want the first value to be selected by default, I need to force the user to select a value from the list to avoid errors where they didn't pick that field and by default a value was assigned.
Is there a more elegant way of doing this than to add code to include an empty value at the top of the list after I get it from the database and before i pass it to the SelectList constructor in my controller class?
The Html helper function takes a 'first empty value' parameter as the third argument.
<%=Html.DropDownList("name",dataSource,"-please select item-")%>
You can also use this way:
dropdownlist.DataTextField = ds.Tables[0].Columns[0].Caption;
dropdownlist.DataValueField = ds.Tables[0].Columns[1].Caption;
dropdownlist.DataSource = ds;
dropdownlist.DataBind();
dropdownlist.Items.Insert(0, new ListItem("Select ...", string.Empty));

Resources