I am trying to create a partialview for my dropdownlistbox in my asp.net mvc 3 application. in my page I have:
@Html.Action("PopulateCombo","ComboController")
controller partialview:
public ActionResult PopulateCombo()
{
//some code here to organise data and maybe some caching
return ItemsForCombo;
}
Is there a better way of templating a Dropdownlistbox?
I would populate the data in the controller, then pass it to a model and finally use an Html.DropDownListFor
. I mean, that's what MVC stands for :)
Example
(PS: it's been quite a while since I not code in c# anymore so apologies for any kind of typo)
controller.cs
Public ActionResult ()
{
Model m = new Model();
//populate data into a list
m.Items = ...
return View(m);
}
model.cs
...
Public List<object> Items { get; set; }
index.cshtml
@using Model // I guess it was something like this
// I cant remember the exact order of the arguments to dropdownlistfor, so just figure it out :)
@Html.DropDownListFor (some arguments)
What are your requirements? Partial view could represent a control that you could re-use throughout your application. I don't think that a drop down list is a good candidate for a partial view.
If I were you and I wanted to display a drop down list, I would use an existing HTML helper.
In my controller I would store values for a drop down list in the view bag:
IList<SelectListItem> selectListItems = new List<SelectListItem>();
// Populate selectListItems
...
// Create a select list. You'll have to replace dataValueField and dataTextField with property names
SelectList mySelectList = new SelectList(selectListItems, "dataValueField", "dataTextField");
// Assume that select list contains a list of countries
ViewBag.Countries = mySelectList;
Then in your view, you can create a dropdown list with HTML helper
@Html.DropDownListFor(m => m.CountryId, (SelectList) ViewBag.Countries);
I wrote this in notepad, so there might be syntax errors.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.