ASP.NET MVC 2 Editor Templates - asp.net-mvc

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.

Related

Specify DropDownList options in MVC 3 Razor

I'd like to know if it is possible to assign a default value for a Dropdownlist while restricting User to select that default value from its option list.
Example :
#Html.DropDownListFor(m => m.Something, new SelectList(Model.TheList), "--DefaultValue--", new { name="SomethingName", id="SomethingID", style="width:150px;"})
Let's suppose TheList contains {"1","2","3"}.
When User clicks the DropDownList, he will find "--DefaultValue--" displayed as initial value, and also find it as one of the options available to be selected.
Is it possible only to have 1,2, and 3 alone as the options without "--DefaultValue--" ?
The only way is to set selected value in DropDown. --Default value-- represents null in selected value
Try this:
#Html.DropDownListFor(m => m.Something, new SelectList(Model.TheList),new { name="SomethingName", id="SomethingID", style="width:150px;"})

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

ASP.NET MVC Dropdownlist retain the selected value in the browser after post

I build a drop down list in my aspx page as following
<%= Html.DropDownList("SelectedRole", new SelectList((IEnumerable)Model.roles, "RoleId", "RoleName", Model.SelectedRole), "")%>
it works fine for first Get and the first default value is selected; then I select item from the drop down list and submit the form.
the controller bind the values correctly,
public ActionResult About([Bind] Roles r)
{
//r.SelectedRole = the selected value in the page.
//Roles r = new Roles();
r.roles = new List<Role>();
r.roles.Add(new Role(1, "one"));
r.roles.Add(new Role(2, "two"));
r.roles.Add(new Role(3, "three"));
r.roles.Add(new Role(4, "four"));
r.SelectedRole = null;
return View(r)
}
Then I nullify the selected item and return my view, but still the previous selected Item is selected (although I did nullify it)
Any Idea if I am doing something wrong or it is a bug in MVC?
I am using ASP.NET MVC 1
Thanks
This is the normal behavior of all html helpers: they will look at the POSTed values to perform the binding. This means that you cannot change the value in your controller action and expect it to reflect on the view if you use the standard helpers. If there's a value SelectedRole in the POST it will always be this value used and the last parameter of the drop down completely ignored.
You could write your own helper to achieve this or redirect after the POST.

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