Mvc DropdownList default selected value by ViewBag - asp.net-mvc

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

Related

Bind Value with DropDownListFor [duplicate]

I am working on an ASP.NET MVC-4 web application. I'm defining the following inside my action method to build a SelectList:
ViewBag.CustomerID = new SelectList(db.CustomerSyncs, "CustomerID", "Name");
Then I am rendering my DropDownListFor as follow inside my View:
#Html.DropDownListFor(model => model.CustomerID, (SelectList)ViewBag.CustomerID, "please select")
As shown I am naming the ViewBag property to be equal to the Model property name which is CustomerID. From my own testing, defining the same name didn't cause any problem or conflict but should I avoid this ?
You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property).
When using #Html.DropDownListFor(m => m.CustomerId, ....) the first "Please Select" option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem> based on the one you have supplied in order to set the value of the Selected property. In order to set the Selected property, it reads the value of CustomerID from ViewData, and the first one it finds is "IEnumerable<SelectListItem>" (not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be).
When using #Html.DropDownList("CustomerId", ....), no data-val-* attributes will be generated and you will not get any client side validation
Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag property will it all work correctly.
There is not harm to use it. You will not get any error. but best practice is to bind model property.

Dropdown in ASP.NET MVC 3

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.

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

Selecting the DropDownList Item Through ViewData

I am putting the current pageSize (5,10,15,20,All) in the ViewData inside the Controller. Now, I am trying to set the DropDownlist to set the selected value to the ViewData value.
#Html.DropDownListFor(x => x.GridItems, new SelectList(Model.GridITems, "Value", "Text",ViewData["SelectedItemItemValue"].ToString()))
The above does not work and the first item is automatically selected when the page calls the action.
The first argument to DropDownListFor should be the item in the Model that you want the selected value to be bound to. For example, if you had a property on your model called 'SelectedItemValue' then your code should be as follows
#Html.DropDownListFor(x => x.SelectedItemValue, new SelectList(Model.GridITems, "Value", "Text",ViewData["SelectedItemItemValue"].ToString()))
(the last argument in the select list constructor is for the selected value so this assumes that you have something with a key of SelectedItemItemValue in your ViewData

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.

Resources