Creating custom text value for ListBoxFor - asp.net

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.

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

Adding additional attributes to CheckBoxList on DataBind

I have a checkbox list that is bound to values from a database, as follows
chkTopLanguages.DataSource = dsSiteLanguages;
chkTopLanguages.DataTextField = "Language";
chkTopLanguages.DataValueField = "LanguageID";
chkTopLanguages.DataBind();
However, I need to also add another value (AltLanguage) to a custom attribute so that I can access this value in some instances. How can I add an additional value attribute to the checkbox items on databind?
You're probably not going to like this, but when I faced this issue before the only way I could see doing it in pure .NET was to do the following:
// Create this field on your data source objects
public LanguageField {
get {
return LanguageID + "_" + AltLanguage;
}
}
chkTopLanguages.DataSource = dsSiteLanguages;
chkTopLanguages.DataTextField = "Language";
chkTopLanguages.DataValueField = "LanguageField";
chkTopLanguages.DataBind();
Then, when you get your values, split the value by "_" and then you can grab both values.

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

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