MVC Drop Down List - asp.net

This construction below using dropdownlist does not work!!
<% = Html.DropDownList (ddlUf, "All", New With (. Class = "text"})%>
It only works if I do this:
<% = Html.DropDownList (ddlUf, "All")%>
Or this:
<% = Html.DropDownList (ddlUf, Nothing, New With (. Class = "text"})%>
How do I solve this problem?
Thanks

use new{ #class = "text"})

I think you have the order of parameters mixed up. Assuming that ddlUf is a string with the DropDownList name, and "All" is supposed to be the default option, then you need something like this:
<% =Html.DropDownList(ddlUf, Model.FullListOfSelectListItems, "All", New With (. Class = "text") %>

There's some parameter order/validity issues here. The Html.DropDownList() method works by taking the following:
string name - assigns a name/id to the control
SelectList selectList - the list of options to appear in the drop down. You can construct this by creating a List and then using Linq to select the items from the list you want to appear in the drop down i.e:
List<string> myList = new List<string>();
//Add items to appear in the drop down.
myList.Add("Item1");
myList.Add("AnotherItem");
...
//Select all the items from the list and place them into a SelectList object.
SelectList dropDownList = new SelectList(from items in myList select items);
string optionLabel - the text for a default, empty item.
object htmlAttributes - a selection of HTML attributes to apply to the control.
So in your example you might want to go for something like:
#Html.DropDownList("MyDropDown", Model.MyConstructedSelectList, "Default item", new { #class = "text" })
For more information on using drop down lists with models in MVC, see this blog post:
http://277hz.co.uk/Blog/Show/10/drop-down-lists-in-mvc--asp-net-

Related

How to use the HTML Helper of Listbox?

I am trying to create a simple Listbox, utilising HTML Helpers and I can't find any resource that guides me through this.
<%= Html.ListBox("listbox_name") %>
And it asks for IEnumerable(SelectListItem) and I dont know how to create one and pass it.
Please help me
Depends on how you want to provide the data for the listbox. If it is static data, you could simply declare a List<SelectListItem> in the view and pass that in:
var mySelectItems = new List<SelectListItem> {
new SelectListItem { Text = "First item", Value = "1" },
new SelectListItem { Text = "Second item", Value = "2" }
};
...
Html.ListBox("listbox_name", mySelectItems)
Otherwise, just get the data from whereever you get it, and pass it in with the model

Multiple selction in Dropdownlist of asp.net MVC 3

Can we select multiple items from razor dropdownlist control. i.e for
#Html.DropDownListFor(m=>m.Country, CountryList as SelectList,"--Select--")
You can try maybe something like this ...
#Html.ListBoxFor(m=>m.Country, new MultiSelectList(CountryList as SelectList, "CountryID", "Select"))
You just have to add a new { "multiple" = "multiple" } as last Parameter of the function - this will render a multiselect.
Given a list of Items (in this example with fields Id and Name), you can start with a List of SelectListItem as follows:
List<SelectListItem> Choices = Items.Select(x => new SelectListItem { Value = Convert.ToString(x.Id).Trim(), Text = x.Name }).ToList();
#Html.ListBox("ListBoxIds", new MultiSelectList(Choices, "Value", "Text"))
In the controller, you will get ListBoxIds as a list of selected Ids.

ASP.Net MVC dropdown selected value

I have been dealing with the dropdownlist which i am able to populate but if i come back to edit a record, the dropdown is not showing the selected value.....
In controller,
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
ViewData["CustomerID"] = qw;
int b = Convert.ToInt32(serviceToUpdate.ServiceID);
var a = datacontext.services.Select(arg => arg.ServiceID).ToList();
ViewData["ServiceID"] = new SelectList(a,serviceToUpdate.ServiceID);
In view:
#Html.DropDownListFor(model => model.ServiceID, ViewData["ServiceID"] as SelectList)
serviceToUpdate,ServiceID has the right value but somehow when I try to edit the selected value is not returned... instead the first value of dropdown is only returned...
I had the same problem. Use the null object pattern where you have a reserved id and the display name of the item is "please choose..." or something similar. Before passing in the model to the view, append to the beginning of the collection the null object. In the controller on the way back in, test for it. You can then set the property to null if the person didn't choose anything.
Here is my question:
DropDownListFor Not Displaying/Persisting Null for First Choice in List
You shouldn't have to use view data explicitly either like you are doing.
Code in Controller:
ViewBag.Services = new SelectList(a, "ServiceId", "#Servicename");
ServiceId is the property representing the key-value for the item displayed in the dropdown list
#Servicename stands for the property representing the text you want to display for the item in the dropdownlist)
Code in View:
#using(#BeginForm){
SelectList services = Viewbag.Services;
#Html.DropDownListFor(model => model.ServiceID, services)
}

Using Html.DropDownListFor() with a SelectList

What is the correct way to populate a SelectList when using the Html.DropDownListFor helper in ASP.Net MVC 3?
I basically have a "Create" form which I want to specify the entry values on for a particular field. For example, it is a movie database and I want the ability to enter a Genre, but I don't want users to be able to enter what they like, so I assume a SelectList to be the best answer?
A way that works is to create a new class with a static method to return the SelectList:
public class Genres
{
public static List<string> GetGenres()
{
List<string> myGenres = new List<string>();
myGenres.Add("Comedy");
myGenres.Add("Romantic Comedy");
myGenres.Add("Sci-Fi");
myGenres.Add("Horror");
return myGenres;
}
}
Which can then be used like this:
<div class="editor-field">
#Html.DropDownListFor(model => model.Genre, new SelectList(OLL.Models.Genres.GetGenres()))
</div>
It just doesn't seem like the right/easiest way to do it? I think I'm missing something obvious here...
Thanks for any assistance you can provide.
This is a simple selectList style I use for drop downs all the time, hopefully you find this helpeful.
ViewBag.AlbumListDD = from c in db.Query<DatabaseEntities.VenuePhotoAlbum>("WHERE VenueId = #0", VenueId)
select new SelectListItem
{
Text = c.Name,
Value = c.Id.ToString()
};
Inside my view:
#Html.DropDownList("AlbumId", (IEnumerable<SelectListItem>)ViewBag.AlbumListDD, new { id = "ChangeAlbum" })
Hopefully you can find this useful as this is a database route to go. I typically like to have all of that sort of information in a database and that way users can dynamically add/remove and change these dropdown items at will. There is a bit of SQL work behind the scenes required when removing a type but it has proven to be very successful and fast for me at this point.
var og = (from s in DB.Products
select new SelectListItem
{
Text = s.ProductName,
Value = s.ProductID.ToString()
});
ViewBag.lstProducts = new SelectList(getproductname, "ProductID", "ProductName");
<p>
#Html.DropDownList("AlbumId", (IEnumerable<SelectListItem>)ViewBag.lstProducts, new { #id = "drp" });
</p>

Create select list with first option text with mvccontrib?

Trying to create a select list with a first option text set to an empty string. As a data source I have a List of a GenericKeyValue class with properties "Key" & "Value". My current code is as follows.
<%= this.Select(x => x.State).Options(ViewData[Constants.StateCountry.STATES] as IList<GenericKeyValue>, "Value", "Key").Selected(Model.State) %>
This gets fills the select list with states, however I am unsure at this point of an elegant way to get a first option text of empty string.
"Trying to create a select list with a first option text set to an empty string." The standard way isn't fluent but feels like less work:
ViewData[Constants.StateCountry.STATES] = SelectList(myList, "Key", "Value");
in the controller and in the view:
<%= Html.DropDownList(Constants.StateCountry.STATES, "")%>
Sure you can, but you add it to your list that you bind to the dropdown...
List<State> list = _coreSqlRep.GetStateCollection().OrderBy(x => x.StateName).ToList();
list.Insert(0, new State { Code = "Select", Id = 0 });
ViewData["States"] = new SelectList(list, "Id", "StateName", index);
Or this...
Your view;
<%=Html.DropDownList("selectedState", Model.States)%>
Your controller;
public class MyFormViewModel
{
public SelectList States;
}
public ActionResult Index()
{
MyFormViewModel fvm = new MyFormViewModel();
fvm.States = new SelectList(Enumerations.EnumToList<Enumerations.AustralianStates>(), "Value", "Key", "vic");
return(fvm);
}
Without extending anything - you can't.
Here's what author says:
One final point. The goal of MvcFluentHtml was to leave the opinions to you. We did this by allowing you to define your own behaviors. However, it is not without opinions regarding practices. For example the Select object does not have any “first option” functionality. That’s because in my opinion adding options to selects is not a view concern.
Edit:
On the other hand - there is 'FirstOption' method for Select in newest source code.
Download MvcContrib via svn, build and use.

Resources