Using DropDownListFor with model - c#

On my view I am using a list as my model and each list item is of type model, so it looks like this:
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
and I am trying to loop through this list and add a specific property to a DropDownListFor:
#for (int i = 0; i < Model.Count(); i++)
{
Html.DropDownListFor(model => model.ElementAt(i).module, new SelectList(Model, Model.ElementAt(i).module));
}
But when I do this it doesn't render a dropdownmenu on my page.
Can someone help?

You can't render a dropdown list for a model because there is no way of representing the model in its entirety in a dropdown. What is ASP.NET supposed to render?
What you can do if you would like to select a model from a list is to run a LINQ Select query on the list, whereby you create an IEnumerable<SelectListItem> like this:
var selectList = Model
.Select(x => new SelectListItem
{
Name = x.module_name,
Value = x.module
});
I have tried to take the values from the screenshot that you posted. Apologies if I made an error. You get the idea...
What this code does is loop through the collection of your object type (Model.Select) and returns a collection of SelectListItem. If you are unfamiliar with LINQ you need to think of Select as a transformative function. It takes a collection, and for each element transforms it into something else and returns the result. Here, it takes each element of the Model collection and creates a SelectListItem. It then returns an IEnumerable<SelectListItem>.
To render the list on the page you do the following:
#Html.DropDownListFor(Model.MyValue, selectList)
...where Model.MyValue is the variable which receives the selected value (assuming that the value, model is a string, which it appears to be).

Related

Binding Field from List of object to a Dropdownlist MVC

I have a list of a certain object, each object contains fields. I need to do a DropDownListFor or DropDownList for that field within that object but its not binding
I initially tried this with a List and this works fine for binding to a normal object field. I then tried converting to SelectList() by doing
#Html.DropDownListFor(model => Model.MyListOfObjects[i].FieldName, new SelectList(Model.MySelectList, "Value", "Text"))
I then tried to set the "Selected" property on the SelectListItem I needed to be selected but still no luck
for (var i = 0; i < Model.MyListOfObjects.Count; i++){
#Html.DropDownListFor(model => Model.MyListOfObjects[i].FieldName, Model.MySelectList)
}
Model.MySelectList is List<SelectListItem>
public List<MyCustomObject> MyListOfObjects {get;set;} //populated
public class MyCustomObject{
public string FieldName {get;set;}
}
So in the end, I need the value of Model.MyListOfObjects[i].FieldName tp be selected from the Model.MySelectList(). The value in the select list does match so I cant see whats wrong
Thank you. Appreciate any help
EDIT: I know I can use "EditorFor" templates for the object used in Model.MyListOfObjects but I would prefer to avoid it if possible as I am using that object with other things so if I need another version of the object in editorfor then I wouldnt be able to do it. As a last resort though, I will just have to change the object to a unique one and go down the editorfor route
selectListItem contains text and value.
You need to bind value field to dropdown not text field.
i.e. model => Model.MyListOfObjects[i].FieldValue
Check This will help you

How do I bind multiple dropdownlists to a list of enums?

I have a model with a property "Countries" of type List. Country is an enum. The list can contain 0-5 countries. When I edit this model, I want to use a dropdownlist for each country in the list. I want to be able to select 0-5 countries for the property by using 5 dropdownlists. How do I do this? For properties with a single enum this works:
#Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.CountryList)
The right country gets selected like it should. For my multi-country property this does not work:
#for (int i = 0; i < 5; i++)
{
#Html.DropDownListFor(model => model.Countries[i], (IEnumerable<SelectListItem>)ViewBag.CountryList)
}
That is, I get my dropdownlists, but the countries doesn't get selected like in the example with the single country.
In my controller I have:
ViewBag.CountryList = new SelectList(Enum.GetValues(typeof(Country)));
Any suggestions? I'm not very good at MVC.
You can use this in MVC5:
#Html.EnumDropDownListFor(m => m.Country)

How to display list returned to strongly typed partial view

I have a form with a lookup. I want to display the results of the lookup in the form so the user can select a result and then it would populate a field on the form (to be submitted with the form). I have a partial view in the form with the search box. That passes a string (pacupc) to the controller. However, I don't know how to display the list that's being return to the partial view.
In my controller:
PriceAssociationLookup pacRep = new PriceAssociationLookup();
return PartialView("_PacSearchResultsPartial", pacRep.GetPacs(pacupc));
definition for GetPacs in class:
IEnumerable<IPriceAssociationLookupRepository> IPriceAssociationLookupRepository.GetPacs(string upc)
{
using (PortalDataEntities entities = new PortalDataEntities())
{
var priceAssociationLookups = (from priceassociationlookup in entities.PriceAssociationLookups
where priceassociationlookup.Upc == upc
select priceassociationlookup).ToList();
return priceAssociationLookups;
}
}
and the partial view the lookup results are being sent to:
#model List<Portal.BusinessModel.Entities.PriceAssociationLookup>
#{
//How to display the list of results?
}
You simply loop them like this:
#model List<Portal.BusinessModel.Entities.PriceAssociationLookup>
#foreach(var price in Model)
{
#price.Upc
}
You can output any of your properties by using the #price.Property notation.
Please note if you are posting the items back you need to use a for loop and index them.

Why does this render as a list of "System.Web.Mvc.SelectListItem"s?

I'm trying to populate a DropDownList with values pulled from a property, and my end result right now is a list of nothing but "System.Web.Mvc.SelectListItem"s. I'm sure there's some minor step I'm omitting here, but for the life of me I can't figure out what it is.
The property GET generating the list:
public IEnumerable<SelectListItem> AllFoo {
get {
var foo = from g in Bar
orderby g.name
select new SelectListItem {
Value = g.fooid.ToString(),
Text = g.name
};
return foo.AsEnumerable();
}
}
The controller code:
public ActionResult Edit(string id) {
// n/a code
ViewData["fooList"] = new SelectList(g.AllFoo, g.fooid);
return View(g);
}
The view code:
<%= Html.DropDownListFor(model => model.fooid, ViewData["fooList"] as SelectList) %>
The problem here is that you shoudn't fill a SelectList with an IEnumerable<SelectListItem>. Use either SelectList or an IEnumerable<SelectListItem>, but not both. For more details, have a look at this question: Asp.Net MVC 2 Dropdown Displaying System.Web.MVC.SelectListItem
I ran into the same problem. You should render your List in the view like
#Html.DropDownListFor(model => model.fooid, new
SelectList(ViewData["fooList"],"Text","Value", Model.DefaultValue))
This is based on c# with razor view
EDIT: This question is very similar to one that was already asked:
ASP.NET MVC 2 - Html.DropDownListFor confusion with ViewModel
Otherwise, you might find this article helpful:
http://www.nickriggs.com/posts/rendering-and-binding-drop-down-lists-using-asp-net-mvc-2-editorfor/
It uses EditorFor, but the same can be done for DisplayFor.

SelectedItem not being remembered in SelectList in ASPNET.MVC

I have the following code which is meant to populate a dropdown with a bunch of integer values and make the currently selected value (in this case, 13) be the selected item.
I've used the same technique but for string values and it works great, remembering each time when I get to the view what the current value is.
In controller:
var x = new[] { 1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
ViewData["Field"] = new SelectList(x, 13);
In view:
<%=Html.DropDownList("Field", (IEnumerable<SelectListItem>)ViewData["Field"])%>
When I debug and watch the ViewData["Field"] object, it does have a selectedValue of 13 and so it must be reaching the View but getting ignored there as all I see on the page is a dropdown with the values 1 to 15, but with 1 showing (none selected so shows the first one)
Is this a bug or am I doing something really stupid?
Thanks
Graeme
I seem to recall that it doesn't actually use the Selected property of the SelectList element. I usually have one ViewData item be the select list and another be the selected value.
Controller:
var x = new[] { 1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
ViewData["Fields"] = new SelectList(x);
ViewData["Field"] = 13;
View
<%= Html.DropDownList("Field", (IEnumerable<SelectListItem>)ViewData["Fields"] ) %>
This was happening to me! I was pulling my hair out for hours, but I eventually figured it out. In my case I was creating a drop-down list like this:
<%= Html.DropDownList("bookId", Model.ProductMenu, new { onchange = "goToBook();" })%>
And it was not printing the selected option. But the dropdown right next to it was working fine:
<%= Html.DropDownList("segmentIndex", Model.SegmentMenu, new { onchange = "goToSegment();" })%>
They were being generated the exact same way in the controller, and the debugger would always show the properly selected value as the view was returned. So what the heck?
The difference was in the view itself. "bookId" in my app happens to be a route/querystring value and segmentIndex is not. Simply changing the name "bookId" in the view to "bookIdBLAH" fixed it!

Categories

Resources