user279
user279

Reputation: 75

How to bind the value in html select option?

I need to bind the value in html select option and I have the values in a C# model. How do I do this? My html code:

 <div class="Div"><span class="label2">values:</span>
    <select id="Binding_values" onchange="values()></select></div>

Upvotes: 1

Views: 5416

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Assuming you have a view model:

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

and a controller action which will populate this view model and pass it to the view:

public ActionResult Index()
{
    var model = new MyViewModel();
    model.Items = new[]
    {
        // TODO: those values could come from a database for example
        new SelectListItem { Value = "1", Text = "item 1" },
        new SelectListItem { Value = "2", Text = "item 2" },
        new SelectListItem { Value = "3", Text = "item 3" },
    };
    return View(model);
}

inside the corresponding strongly typed view you could use the DropDownListFor helper:

@model MyViewModel
...
@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.SelectedValue, Model.Items)
    <button type="submit">OK</button>
}

and if this dropdown is inside an HTML for posting back to the controller you could have an action that will retrieve the selected value from the model:

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    // model.SelectedValue will contain the selected value from the dropdown list here
    ...
}

Assuming you want to send the selected value to the server immediately after changing the selection in the dropdown without clicking on a form submit button you could give this DropDownList an unique id:

@Html.DropDownListFor(x => x.SelectedValue, Model.Items, new { id = "myDdl" })

and then subscribe to the .change() event of this dropdown using jQuery and submit the containing form:

$(function() {
    $('#myDdl').change(function() {
        $(this).closest('form').submit();
    });
});

Upvotes: 2

Related Questions