1

I need to generate a dynamic dropdown list in a partial view using ASP.NET MVC 2.

controller:

[HttpGet]
        public ActionResult GetDestinationList()
        {
            JqGridClientRepository rep = new JqGridClientRepository();
            IEnumerable<Client> clients = rep.GetClients();
            var li = from s in clients
                     select new
                     {
                         Company = s.Company
                     };
            return PartialView(li);
        }

Below is the view i'm having currently and i need to bind the values to the select list returned by the controller.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>

   <select> 
    <option value="1">One</option> 
    <option value="2">Two</option> 
    ...
</select>

2 Answers 2

2

As always you could start by writing a view model:

public class MyViewModel
{
    public string SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }
}

and then have your controller action populate this view model and pass it to the view:

[HttpGet]
public ActionResult GetDestinationList()
{
    JqGridClientRepository rep = new JqGridClientRepository();
    IEnumerable<Client> clients = rep.GetClients().ToList();
    var model = new MyViewModel();
    model.Values = clients.Select(x => new SelectListItem
    {
        Value = x.SomePropertyYouWantToBeUsedAsAValue,
        Value = x.SomePropertyYouWantToBeUsedAsText,
    });
    return PartialView(model);
}

and then make your view strongly typed to this view model and use the DropDownListFor helper:

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<MyViewModel>" 
%>
<%= Html.DropDownListFor(x => x.SelectedValue, Model.Values) %>

In the controller action you could perform whatever dynamic query you want to retrieve the data. The important bit is that you need to constitute an IEnumerable<SelectListItem> where each element represents respectively the Value and the Text used in the dropdown.

Sign up to request clarification or add additional context in comments.

Comments

0

You can bind like this, Your view will be like this:

<div class="form-field-bg">
                @Html.LabelFor(m => m.ClientName)<div class="validate-star"></div>
                @Html.DropDownListFor(m => m.ClientName, ViewBag.ClientList as IEnumerable<SelectListItem>, new { @class = "dropdown-field" })
            </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.