Dropdown in ASP.NET MVC 3 - asp.net-mvc

I am new to MVC so probably confused . can somebody please explain me the dropdown in razor.my questions are-
What is the difference in dropdownlist and dropdownlistfor
how do i Pass ID column of my database table as value and NAME column as text.
How do i add "other" to the dropdownlist.
how do i access the selectedlistitem in code behind.
if possible please explain with an example.

DropDownList is generated by code like this:
#Html.DropDownList("PersonId", new SelectList(Model.People, "Id", "Text");
On the other hand, DropDownListFor is generated like this:
#Html.DropDownListFor(m => m.PersonId, new SelectList(Model.People, "Id", "Text")
Problem with DropDownList is that it has a magic string and if you decide to refactor the model later on, there's a high change you'll forget to change the magic string too.
You could do a LINQ query like this:
var datalist = New SelectList(from x in _peopleService
select new SelectListItem { Text = x.Name, Value = x.Id});
If you don't have a service or an ORM between it you need to apply it to your situation, but you can generate a list like that.
After nr 2, you can
datalist.Add(new SelectListItem() { Text = "Other", Value = "-1"});
Also you have to put that datalist in your viewmodel/model that is passed to the View, so you can generate a selectlist item with that. In this case you could just do:
#Html.DropDownListFor(x => x.PersonId, Model.PersonList);
if you stored the list as PersonList in Model.
In your Viewmodel (Well, model in mvc) you have a property where the selected item will be stored, look at the 1st question - In this instance the selected item's id will be stored in the PersonId property.

Related

Mvc DropdownList default selected value by ViewBag

I have filled a viewbag and bound a dropdownlist to it ..like below
var countrylist = ctx.Countries.ToList();
ViewBag.countrylist = new SelectList(countrylist, "ID", "Name",2);
#Html.DropDownList("countrylist", (IEnumerable<SelectListItem>)ViewBag.countrylist, "-Select-")
Above I wanted to by default select the second item of countrylist, so I mentioned the value "2" as last parameter of the ViewBag countrylist overload.
But it is not selecting that item by default.
However, If I change the dropdownlist name to something else like below
#Html.DropDownList("countrylist12345", (IEnumerable<SelectListItem>)ViewBag.countrylist, "-Select-")
then it will by default select the 2nd item in countrylist.
Please explain why this is happening ?
Your whole view is most likely strongly typed with some model
#model YourNamespace.SomeModel
This model has a field countrylist which has some value, maybe 0 by default. And because the name of this field is the same as the name of the dropdown itself, the value of this field is what the dropdown uses to determine the default selection. Once you change the name of the dropdown, the connection is gone.
What you can do is make sure that this model you use to strongly type your view is being assigned some value in countrylist field. For example, inside the controller:
SomeModel model = new SomeModel();
model.countrylist = 2;
return View(model);

DropDownListFor enums in EF5 selected item

Like in DropDownListFor enums in EF5 I would like to generate a dropdown list from a code first EF enum. The solution provided works but it does not set the selected value. How I can do this? I have tried the code below but it does not work (where the last parameter in SelectList re-represents the selected value:
#Html.DropDownListFor(model => model.TypeID, new SelectList(Enum.GetValues(typeof(Models.OrganisationType)),model.TypeID))
I have answered my question. The above code correctly sets the selected value in the dropdown. For some reason MVC did not like my enum and property names when I used the word 'Title' for my property and 'Titles' for my enum as below:
#Html.DropDownListFor(model => model.Title, new SelectList(Enum.GetValues(typeof(BL.Titles)),Model.Title),"")
Also I am using one View for both Create and Edit and therefore had to add code to stop MVC trying to set the selected value before the object has been created:
#if(Model == null) {
#Html.DropDownListFor(model => model.PersonsTitle, new SelectList(Enum.GetValues(typeof(HLRA.eForms.BL.PersonsTitle))),"")
}
else
{
#Html.DropDownListFor(model => model.PersonsTitle, new SelectList(Enum.GetValues(typeof(HLRA.eForms.BL.PersonsTitle)),Model.PersonsTitle),"")
}
Does anyone know a more elegant way?
This:
#Html.DropDownListFor(model => model.PersonsTitle, new SelectList(Enum.GetValues(typeof(HLRA.eForms.BL.PersonsTitle)))))
should be enough.
I don't like your condition:
#if(Model == null)
You should have your Model defined and the property "PersonsTitle" should be set with your default value.

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"))

ASP.NET MVC 2 Editor Templates

The following link explains editor templates: http://weblogs.asp.net/scottgu/archive/2009/07/31/asp-net-mvc-v2-preview-1-released.aspx
What I want to know is if I have a editor template for a drop down, how is the initial value set?
I have a drop down and I use the Html.EditorFor(c => c.Country, "CountryDropDown")
But it always defaults to the first selected item in the list... any ideas?
I would think, you need to create a viewdata, or create a viewmodel to include the select list passing to the dropdown list. For example, in your controller action, you should do sth like this:
//get your item for editing here i.e named itemToEdit
//get your country collection here
ArrayList countryList=New ArrayList;
foreach (Country c In YourCountryCollection)
{ countryList.Add(New With {.Item = c.CountryName, .value = c.CountryID})
}
Viewdata("CountryList")=New SelectList(countryList, "Value", "Item", itemToEdit.countryID)}
Now in your view, instead of using html.editorfor, you should uuse the following:
Html.Editor("CountryLis", "CountryDropDown")
This should set your dropdownlist with the selected value.
Hope this help.

HTML.DropDownList does not respect pre-selected value

I want to use Html.DropDownList(string name, IEnumerable SelectList, Object htmlAttributes) to render a select list with a preselected value for me.
My select list is in the model object of my view, so I have been writting the following code:
<%= Html.DropDownList("aName", mySelectList, new { }) %>
Which will render the select list without the pre-selected value.
A workaround I have found is passing the SelectList as ViewData and doing the following:
In the controller:
ViewData["TimeZones"] = mySelectList;
In the view:
<%= Html.DropDownList("TimeZones", null, new { }) %>
This way the select list will be rendered with the preselected value, however, I don't want to be forced to pass my select list as view data. What am I doing wrong? Thank you in advance for your help.
You can simply do this (it works):
<%: Html.DropDownList("DropdownName", new SelectList(ListItems, "Value", "Text", selectedItem), htmlAttributes)%>
Let me know in case this does not work for you.
Autobinding the selected item
The other approach is to automatically bind the selected item, and passing the list of items as parameter to the DropDownList helper method.
In the controller you do exactly the same thing as before, just don’t set to true the Selected property of any item. Then you also have to put into the view model the value of the item you want to select.
var model = new IndexViewModel()
{
ListItems = items,
SelectedItem = 2
};
And finally in the view, you use the overload which accepts also the selectList parameter:
<%= Html.DropDownList("SelectedItem", Model.ListItems) %>
The only difference in the HTML rendered is that, with first approach, the name of the HTML select element is ListItems, with the second it is SelectedItem.
These approaches are fine if you are creating your own list, but they are not the optimal solution if you are receiving the list of options for an external method, for example from a DB repository.
Take a look at this link
I know this is an old post, but I ran into a similar issue in MVC5. The solution is simple, but I struggled with it for a while, so I thought I'd share.
VS auto-generates DropDownLists with this in the view:
#Html.DropDownList("EpisodeTypeId", null, htmlAttributes: new { #class = "form-control" })
In the controller, VS auto-generates the ViewBag code differently for a Create vs. and Edit.
Here's the code from a create:
ViewBag.EpisodeTypeId = new SelectList(db.EpisodeTypes, "Id", "Name");
And from an edit:
ViewBag.EpisodeTypeId = new SelectList(db.EpisodeTypes, "Id", "Name", episode.EpisodeTypeId);
That fourth argument is important for Edits, as you might expect. If you leave it out, the database value for that record will not be pre-selected in the DropDown.
The VS auto-generated code will be correct, but if you're adding in fields manually later, this is easy to miss.

Resources