MVC SelectList not working - asp.net-mvc

List<SelectListItem> items = new List<SelectListItem>();
if (a)
{
SelectListItem deliveryItem = new SelectListItem()
{
Selected = a.selected,
Text = "Delivery",
Value = "1"
};
items.Add(deliveryItem);
}
if (b)
{
SelectListItem pickupItem = new SelectListItem()
{
Selected = b.selected,
Text = "Pickup",
Value = "2"
};
items.Add(pickupItem);
}
SelectList selectList = new SelectList(items);
ViewData["OrderTypeList"] = selectList;
Then using it with
Html.DropDownList("OrderTypeList")
Renders
<select id="OrderTypeList" name="OrderTypeList"><option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
</select>
Why it is not rendering options properly?

The constructor method you're calling when you do:
SelectList selectList = new SelectList(items);
Creates a set of SelectListItems that themselves point to SelectListItems (hence the weird option since it just calls ToString on the object). Instead set your list to the ViewData key directly
ViewData["OrderTypeList"] = items;

You could have also simply changed the one line from:
SelectList selectList = new SelectList(items);
to
SelectList selectList = new SelectList(items, "Text", "Value");
This will instruct MVC which properties to use as the Text and Value in your option tags.

Or you could create a class that will hold the select list and then return the class as the views model. I think that's a much more elegant way of doing it rather than ViewData.
public class MyFormViewModel
{
public SelectList Friends { get; set; }
}
Then in your ActionResult
MyFormViewModel fvm = new MyFormViewModel();
fvm.Friends = new SelectList(myList, "UserName", "NickName");
Then in your view
<%= Html.DropDownList("ToUserName", Model.Friends, new { #class = "field" })%>

If you look at the Intellisense for the SelectList constructor overloads, the code SelectList(items) should work, but doesn't. The fact that it simply does a ToString() on items is, as far as I can tell, a bug that Microsoft should fix. The answers are all nice workarounds. BTW, if you use the method supplying "Text" and "Value", the correct answer should be
SelectList selectList = new SelectList(items, "Value", "Text")
not
SelectList selectList = new SelectList(items, "Text", "Value")
At least, that agrees with my experimentation in MVC 3.

I think you should try rendering with
Html.DropDownList("OrderTypeList", ViewData["OrderTypeList"])

Related

MVC 5 DropDownListFor Database Linq;

Can anyone please tell me how to write Controller for C# (public ActionResult DropList()) for Drop Down List generate Linq I want convert this SELECT DISTINCT CouName FROM Locations; to Linq for my drop down list dynamically generate.
Chtml page how do I write in #Html.DropDownListFor("")
Models.Location
This code will generate a select list from an IQueryable GetAll() method, or you could use it on your entity directly using from c in _context.Set<Location>()
public SelectList GetAsSelectList()
{
var locs = from c in GetAll()
select new
{
Id = c.Id,
Name = c.Name
};
return new SelectList(locs, "Id", "Name");
}
Where Id is the Value field and Name is the Text field of the selectlist options.
This would be assigned to a model property:
var model = new MyModel
{
LocationList = GetAsSelectList();
}
You would pass the model to your View, and use DropDownListFor:
#Html.DropDownListFor(x => x.MyModel.Location, Model.LocationList)
Your model would also have a Location property which you would set to display a default value if you wanted to do that.
Assuming you model is named MyModel
Controller
public ActionResult Edit()
{
var couriers = // get your couriers from the database using your query
// Is better to assign this to a property in your view model, but ViewBag will do for now
ViewBag.CourierList = new SelectList(couriers);
var model = new YourModel();
}
View
#model YourModel
#using(Html.BeginForm())
{
#Html.DropDownListFor(m => m.CouriersName, (SelectList)ViewBag.CourierList)
}
As far as i have understood, you can do something like this:
public ActionResult DropList()
{
List<SelectListItem> objResult = new List<SelectListItem>();
var result = dbContext.Locations.Select(x=>x.CouName).Distinct().ToList();
foreach(var item in result)
{
SelectListItem temp = new SelectListItem();
temp.Text = item;
temp.Value = item;
objResult.Add(temp);
}
ViewBag.DropdownResult = objResult;
return View();
}
Dropdown in view:
#Html.DropDownListFor(m=>m.ModelLocations, ViewBag.DropdownResult as List<SelectListItem>)
Please modify the code as per your need.
using System.Web.Mvc;
...
public static List<SelectListItem> GetItemsForDisplay(string listName)
{
//your data access function should return a list of objects
return DAL.Table.SelectByName(listName)
.Select(x=> new SelectListItem{Text=x.DisplayName, Value=x.ID})
.ToList<SelectListItem>();
}

Dropdownlist client side required validation (without model)

View:
#Html.DropDownList("CategoryItems", null, new { #class = "ddlcs" })
#Html.ValidationMessage("CategoryItems")
Controller:
var cat = from s in db.CategoryDbSet
where s.IsActive == true
orderby s.CatName
select new { s.CatID, s.CatName };
var catListItems = cat.ToList()
.Select(c => new SelectListItem
{
Text = c.CatName,
Value = c.CatID.ToString()
})
.ToList();
catListItems.Insert(0, new SelectListItem
{
Text = "[--Select the category--]",
Value = ""
});
ViewBag.CategoryItems = catListItems;
I wish to enforce the required validation on the dropdown when someone selects the "Select the category" option during the save action. I am new to MVC framework and i am not sure where am i making the mistake ? This dropdown is not tied up with the Model.
Please suggest the soln.
This dropdown is not tied up with the Model.
That's the mistake. Validation in ASP.NET MVC works by decorating your view model properties with the respective attributes. For example if you want to make this dropdown required, you would decorate the corresponding property on your view model with the [Required] attribute.
So add the necessary properties to your existing view model:
public class MyViewModel
{
[Required]
public int? SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
... some other properties that your view might need
}
and then in your controller action populate this view model:
var model = new MyViewModel();
model.Categories = cat
.ToList()
.Select(c => new SelectListItem
{
Text = c.CatName,
Value = c.CatID.ToString()
}).ToList();
return View(model);
and in your view use the strongly typed versions of the helpers:
#Html.DropDownListFor(
x => x.SelectedCategoryId,
Model.Categories,
"[--Select the category--]",
new { #class = "ddlcs" }
)
#Html.ValidationMessageFor(x => x.SelectedCategoryId)
If you want only client side validation, you may do this:
$('form').validate({
rules:{
CategoryItems: 'required'
}
});
Working demo.
But I wouldn't suggest doing so as the client side validation is for better user experience and can be easily bypassed. The correct way to do this is described in Darin's answer, using dataannotations and view models.

Html.DropDownList populating

I have a drop down in my MVC project.
#Html.DropDownList("Chart Type", new List<SelectListItem>
{
new SelectListItem{ Text="Horizontal", Value = "Horizontal" },
new SelectListItem{ Text="Vertical", Value = "Vertical" },
new SelectListItem{ Text="Pie", Value = "Pie" }
},
new { #class = "chzn-select", #multiple ="true", #style="width:350px;"} )
This puts hard coded values in the list.
If I want to get the values from a database, what is the best approach?
Can I have the Html.DropDownList reference a sql query or SP for populating the list?
Create a view model with (at least) two properties:
public class ViewModel()
{
public List<SelectListItem> Items { get; set; }
public string SelectedItem { get; set; }
}
In your controller, make the call to your data source and populate the Items property of the view model and pass it to the view.
public ActionResult Index()
{
var viewModel = new ViewModel();
viewModel.Items = database.GetChartTypes();//or however you're accessing your data
return View(viewModel);
}
Then strongly type your view and use the DropDownListFor helper
#model MyProject.ViewModel
...
#Html.DropDownListFor(m => m.SelectedItem,
Items,
"--Select a Chart Type--",
new { #class = "chzn-select",
#multiple ="true",
#style="width:350px;"
});
You do not want the UI making calls to your data layer.
What you would want is the controller either calling a "service" that then calls the repository, or the controller calling the repository to get the list.
Once it has the list, it will pass that to the view using a ViewModel or the ViewBag.

MVC DropDownListFor SelectedValue with collection issue

First of All Sorry to post the same question thought there are lot of posts already available. I tried all possible ways and finally I dint have any other option other than posting the same question.
I wanted to bind a enum to a DROPDOWNLISTFOR, but the text in a friendly manner. so In the controller I am binding the selectlist like
List<SelectListItem> formTypeSelectList = new List<SelectListItem>();
foreach (FormType type in ItemHelper.EnumToList<FormType>())
{
SelectListItem formTypeList = new SelectListItem();
formTypeList.Text = ItemHelper.GetEnumDescription(type);
formTypeList.Value = Convert.ToString((int)type);
formTypeList.Value = Convert.ToString((int)type);
formTypeSelectList.Add(formTypeList);
}
item.FormTypeSelectListItem = formTypeSelectList;`
My Entity has
public FormType FormType { get; set; }
public List<SelectListItem> FormTypeSelectListItem { get; set; }
public SelectList FinalSelectList
{
get
{
return new SelectList(FormTypeSelectListItem, "Value", "Text", (int)FormType);
}
}
My view has
<%= Html.DropDownListFor(x => x.Item.FormType, Model.Item.FinalSelectList, new { id = "ddlFormType" })%>
I even tried few other option for binding views like
<%= Html.DropDownListFor(x => x.Item.FormType, new SelectListItem(Model.Item.FinalSelectList,"Value","Text",(int)Model.Item.formType)) %>
Nothing works, When I changed to HTML.DropdownList with a name specified it worked perfectly, but i wanted to bind with dropdownlistfor only.
I even tried adding different id, different name in view like
new{id="ddlformType",name="ddlformtype")
nothing worked. Can some one help me to fix this?
Thanks,
Akila
DropDownListFor is looking for an IEnumerable<SelectListItem> for it's items. Try just passing your FormTypeSelectListItem to the DropDownListFor method in place of your FinalSelectList. You may have to cast the model property as an IEnumerable<SelectListItem>

ASP.Net MVC Drop Down List

I am developing an ASP.Net MVC 3 Web application and believe my method of returning a list of items to a drop down list in the View is a bit long winded. Let me explain.
I have a ViewModel which contains an Equipment Entity and a SelectList to display a list of Categories.
public class AddEquipmentViewModel
{
public Equipment equipment { get; set; }
public SelectList categoryList { get; set; }
}
In the GET create method of my Equipment Controller, I return my ViewModel to the view, see below:
//Add new select list item named 'Please select option' to the top of list
var categoryList = categoryService.GetAllCategories();
var categorySelectListItems = categoryList.Select(c => new SelectListItem { Value = c.categoryID.ToString(), Text = c.categoryTitle }).ToList();
categorySelectListItems.Insert(0, new SelectListItem { Text = "Please select option", Value = string.Empty });
AddEquipmentViewModel viewModel = new AddEquipmentViewModel
{
equipment = new Equipment(),
categoryList = new SelectList(categorySelectListItems.ToList(), "Value", "Text")
};
I know I could discard the extra code before I create an instance of my ViewModel and just assign my Category List to the relevant ViewModel property like so
categoryList = new SelectList(categoryService.GetAllCategories(), "categoryID", "categoryTitle")
However, this then just returns a list of categories to my drop down list in my View, whereas, I would like to add a new SelectListItem, ie, "Please select option".
I just feel that my approach to manually adding a new SelectListItem to my SelectList is a bit cumbersome and I would greatly appreciate if someone could share a better method?
Thanks for your time.
<%= Html.DropDownList("name", new SelectList(...), "Your Combobox default message")%>
Hope it helps

Resources