Creating DropDownListFor items in the view
Asked Answered
E

2

5

I want to create a DropDownList with a binding for one of my model data, but i want the dropdown items to be built within the View and i do not want the items coming in the Model data or from my controller. Can you please suggest how to build the selectlist within View Basically I want to create something like this:

<%= Html.DropDownListFor(model=>model.SomeProperty,<<create the dropdown list items here>> %>

Please suggest.

-Sampat.

Endanger answered 2/1, 2012 at 7:17 Comment(1)
Why don't you want the items coming from the view? The view should just present data. Why can't you use a view model? I have a drop down sample at code.msdn.microsoft.com/Using-the-DropDownList-67f9367dBismuth
T
6

You can't use it that way. As the name suggests its for returning an HTML select element for each property in the object that is represented by the specified expression using the specified list items and HTML attributes.

Though you can create this list object in view like following :-

@Html.DropDownListFor(model => model.DropDownElement, 
                       new SelectList(model.DropDownElement, "Id", "Name"))

Update

I will take the example of a Country Model with an Id/Name pair. Like following

public class Country 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Now, in your controller action, you can pass it as a selectlist:

public ActionResult YourAction()
{
    YourModel yourModel = new YourModel(); // Just for reference. I suppose you must be passing some model to your view
    ViewBag.DropDownList = new SelectList(db.Countries, "Id", "Name"); // This way you don't need to make any changes with your passing model.
    return View(yourModel);
}

And finally in View, you can use the DropDownListFor in the following manner.

@Html.DropDownListFor(model => model.YourModelProperty, 
   (IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---") 

On a Sidenote, if you just want to display a list of numbers with value, you can directly enter the HTML and utilize it, rather than using the DropDownListFor. Like follwing

<select id="yourModelPropertyName" name="yourModelPropertyName">
   <option value="">---Select Value---</option>
   <option value="1">India</option>
   <option value="2">Australia</option>
   <option value="3">US</option>
   <option value="4">England</option>
   <option value="5">Finland</option>
</select>

Just make sure that "yourModelPropertyName" is correct and it should be the one for the property where you want it updated

More update

In the views where you wan't to show the selected value, use below code

<select id="yourModelPropertyName" name="yourModelPropertyName">
   <option selected="selected" value="1">@model.YourDropDownList</option>
   <option value="2">India</option>
   <option value="3">Australia</option>
</select>

This shall do the trick :-)

Totem answered 2/1, 2012 at 7:27 Comment(10)
The property to be updated is just one integer which gets updated based on selected item in the dropdown, in your example "DropDownElement" is my int value in DB, now I need a list to be shown in the dropdown which is static name/value pair and bind the selected value to the property while submitting the model.Endanger
I have edited my answer with more illustrated example. Hope it helpsTotem
BTW the View code is of Razor syntax. You will need to remove "@" and place "<%" at the start and "%>" at the end.Totem
Thanks Pankaj for the details.Endanger
@Sampat, I hope you have understood everything. I have added one more thing to the answer and that is to manually produce the list in viewTotem
I am using the second method where I have mapped my Model property to the id and name and rendering it directly in HTML. So I am able to update the Model but when I display the Model I want the selected item to be value coming from the Model. I am able to achieve this through jquery(onLoad), but is there a way to bind my model value to the dropdown and show the selected item.Endanger
There is nothing difficult in this. All you need to do is add the selected property to the corresponding option element like this : <option selected="selected" value="2">Australia</option>Totem
I know the html syntax for selecting the dropdown item, but the value of the selected item is coming in the Model object. As per the example the selected item's value would be in Model.yourModelPropertyNameEndanger
In jQuery i am selecting the item to be shown as selected. From your example the html in the view would remain same(<select>....</select>) but on the document load the jquery would be something like this: $("#yourModelPropertyName").val(<%=Model.yourModelPropertyName%>); This works well, i am exploring options on how to get it selected by default while I get it from the server side without any client side work.Endanger
This is not the problem. Based on the model value i.e 1,2 or 3 I need to set that particular item as selected i.e if I get the model.yourPropertyName as 2 then selected item should be India.In your solution the model value is set as one of the dropdown item.Endanger
A
1

@Pankaj gave you a rough way of doing it. You can also pass the IEnumerable of SelectListItem object tobject to your view from controller and create your select element based on that.

Here is a good example:

A Way of Working with Html Select Element (AKA DropDownList) In ASP.NET MVC

Imagine that your controller looks like something like this:

public ActionResult Index() {

    var products = productRepo.GetAll();

    registerProductCategorySelectListViewBag();
    return View(products);
}

private void registerProductCategorySelectListViewBag() {

    ViewBag.ProductCategorySelectList = 
        productCategoryRepo.GetAll().Select(
            c => new SelectListItem { 
                Text = c.CategoryName,
                Value = c.CategoryId.ToString()
            }
        );
}

on your view, DropDownListFor html helper should look like something like this:

@Html.DropDownListFor(m => m.CategoryId, 
    (IEnumerable<SelectListItem>)ViewBag.ProductCategorySelectList
)
Arvy answered 2/1, 2012 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.