How to use the HTML Helper of Listbox? - asp.net

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

Related

How to set a default value in a DropDownListFor

I've been working on this for 2 days and I can't make it work. I'm trying to make a DropDownListFor with a default value (Like in an Edit page). I made it work without a model but when there is a model, it shows the first item as the default not the one I wanted.
I tried adding a Selected = true in a SelectListItem while being in a foreach loop like this, still not working:
List<SelectListItem> selectListCategories = new List<SelectListItem>();
foreach(var item in listCategories)
{
if(item.Id == Model.Category.Id)
{
selectListCategories.Add(new SelectListItem { Value = item.Id.ToString(), Text = item.Name, Selected=true });
}
else
{
selectListCategories.Add(new SelectListItem { Value = item.Id.ToString(), Text = item.Name });
}
}
This one worked but without a model.
I also tried adding a default value in the SelectList object like that :
#Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.ListingCategories, "Id", "Name", Model.Category.Id))
It either didn't work or there is something I didn't understand correctly because I tried adapting some example I saw here and on msdn posts without any success.
ViewBag.ListingCategories contains a IEnumerable list of my categories taken from my database.
Of course, Model.Category contains a Category object with an Id (this is a Foreign Key to another table) and a Name.
Now I'm out of option so hopefully I can find help here.
Thanks.
See this answer (by #Elad Lachmi):
SelectListItem has a Selected property. If you are creating the
SelectListItems dynamiclly, you can just set the one you want as
Selected = true and it will be the default.
SelectListItem defaultItem = new SelectListItem()
{
Value = 1,
Text = "Deafult Item",
Selected = true
};

HTML Select control does not have selected value when generated with Razor DropDownListFor

I have a view in asp.net/mvc4/razor application where I want to edit value of model using dropdownlist control. I use it this way:
#Html.DropDownListFor(m => m.DateFormat, new SelectList(new [] {"mm/dd/yyyy", "dd/mm/yyyy"}))
The value of DateFormat property is set to one of those values in model but when I load the view, the html select is always set to first value. Am i missing sth?
UPDATE:
This was driving me nuts for two days. Finally I changed the name of property and it started to work. I think it somehow conflicted with value I stored in ViewData/ViewBag collection under the same key. I am not yet sure why. Maybe somebody can explain that?
Try your SelectList something like this where you define the text and the value, along with the selected item.
#(Html.DropDownListFor(m => m.DateFormat, new SelectList
(
new List<Object> {
new {
value = "mm/dd/yyyy", text = "mm/dd/yyyy"
},
new {
value = "dd/mm/yyyy", text = "dd/mm/yyyy"
}
}, "value", "text", Model.DateFormat)
))
This code is untested
Make the SelectList a buddy property of the model.
public class MyModel(){
prop DateTime MyDate {get;set;};
prop SelectList SelectDates {get;set;}
}
Then populate the SelectList after you have selected your date (remember to do this every time you build your model):
SelectDates = dates.Select(d => new SelectListItem
{
Value = d.ToString(),
Text = d.ToString(),
Selected = d == MyDate
})
Then use the property when you build your dropdown:
#Html.DropDownListFor(m => m.DateFormat, Model.SelectDates ))

Creating custom text value for ListBoxFor

So my initial need is that I need to display two properties in the MVC control ListBoxFor. Basically I want to do something like this:
#Html.ListBoxFor(m => m.ContractLocations, new SelectList(Model.ContractLocations, "CUSTNMBR", "CUSTNAME" + " - " + "CUSTNMBR" ), new { #class = "form-control row marb10", size = 15 })
But obviously it won't let me do that. So I am assuming that I need to create a custom property in my ViewModel? But I'm not really sure how to combine two strings within my model? Basically I want to create something similar to a ko.computed where it adds the two values together and then I can display it on my ListBox control. Although I might be thinking about this all wrong and maybe there is an easier alternative?
So what is the best option to accomplish this?
Add a list property to your model:
public IEnumerable<SelectListItem> ContractLocationsList { get; set; }
In your Action, build your list, something like:
myModel.ContractLocationsList = new List<SelectListItem>() {
new SelectListItem() { Value = Customer.Id, Text = Customer.Name + " - " + Customer.Number }
};
And now in your View, you can simply:
#Html.ListBoxFor(m => m.ContractLocations, Model.ContractLocationsList, ...)
Notice that ContractLocationsList holds the list of values to select from, while ContractLocations holds the actual selected values.

ASP.NET MVC4 Building Custom Controls

I want to reuse an combo box control which occurs in various modules in our project.
Combo box with Select, Yes and no items in it.
#Html.DropDownList("SampleList", new[]
{
new SelectListItem() {Text = "Yes",Value = "1" },
new SelectListItem() {Text = "No",Value = "2" }
},"Select")
What approach would be better?
To use Partial View or User Controls?
Also in certain forms they are repeated multiple time.
This is a questionnaire page.
Let me know if any further options are available as i am new to MVC. Thanks in advance.
To use Partial View or User Controls?
MVC doesn't have any notion of "user controls", partial views are pretty much the equivalent so they would be the most logical choice.
In a form if were to use it in 4 different places then i will be able to call using #Html.Partial but how do i differentiate between the four controls?
Just make your partial view take in the ID field e.g.
#model string
#Html.DropDownList(Model, new[]
{
new SelectListItem() {Text = "Yes",Value = "1" },
new SelectListItem() {Text = "No",Value = "2" }
}, new { id = "#Model" })
Which you could then call like
#Html.Partial("SelectList", "ddlOne");
#Html.Partial("SelectList", "ddlTwo");
#Html.Partial("SelectList", "ddlThree");

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>

Resources