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>
Related
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.
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
how can i get a form field id after submitting the form. im trying like this:
ViewData.TemplateInfo.GetFullHtmlFieldId(logOnParts.Part.UserNameOrEmail)
but no work on controller side. i need to get "Part_UserNameOrEmail" something..
if (String.IsNullOrEmpty(logOnParts.Part.UserNameOrEmail))
{
ModelState.AddModelError("Part_UserNameOrEmail", "error");
TempData["logon-focus-field"] = "Part_UserNameOrEmail";
}
so i will focus the field on view side like this:
$(document).ready(function () {
$('#TempData["logon-focus-field"]').focus();
});
A controller should absolutely not need such information. The generated id is a view specific information. If you need this in a controller this simply means that you have some serious design problem with your application. Unfortunately as you haven't explained your scenario in the question it is difficult to help you solving this problem. So in your controller you could do this:
Expression<Func<MyViewModel, string>> expression = x => x.Part.UserNameOrEmail;
string name = ExpressionHelper.GetExpressionText(expression);
string id = new TemplateInfo().GetFullHtmlFieldId(name);
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)
}
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.