Bind Mvc Model using with html <select> tag

16,765

Solution 1

element needs a name attribute to match the model property. add CityId in name attribute of select tag:

<div><select id="ddlCity" name = "CityId"></select></div>

Solution 2

the <select> tag need MVC Name property to add, @Html.NameFor(x=>x.Entity Property) and name property bind value in model. html code below :

<div><select id="ddlCity" name="@Html.NameFor(c=>c.CityId)"></select></div>

thanks for responding to answer this topic.

Share:
16,765
Naimish Mungara
Author by

Naimish Mungara

I am Asp.net and C# web Devloper

Updated on July 31, 2022

Comments

  • Naimish Mungara
    Naimish Mungara almost 2 years

    i have one drop down list, this list bind value using ajax call

    <script type="text/javascript">
    function getCityName(data) {
        $('#ddlCity').empty();
        if (data != 0) {
            $.ajax({
                type: "POST",
                url: "/Home/GetCityList",
                data: { 'CityId': data },
                cache: false,
                //contentType: "application/json",
                datatype: "JSON",
                success: function (result) {
                    var cityData = result.Data;
                    var defaultV = new Option("--Select--", 0, true);
                    $('#ddlCity').append(defaultV);
                    for (var i = 0; i < cityData.length; i++) {
                        var opt = new Option(cityData[i].CityName, cityData[i].Id);
                        $('#ddlCity').append(opt);
                    }
                }
            });
        }
        else {
            alert('Select State');
        }
    }
    

    <div>@Html.LabelFor(c => c.CityId)</div>
    <div><select id="ddlCity"></select></div>
    

    hear i want to bind model prop CityId in model class how to bind it...

  • CodeCaster
    CodeCaster over 7 years
    Yes, that's a very nice explanation of how you can bind a select list in MVC 5, but what's the relation to the OP's JavaScript-laden question?
  • Barry Franklin
    Barry Franklin over 7 years
    This doesn't bind the CityId value - it only selects an option in the drop down if a CityId value exists in the model. I'm pretty sure, since he's using a select, that he wants the user to be able to "select" (change) a value and have it be bound to the selected value (CityId) in the model.
  • CodeCaster
    CodeCaster over 7 years
    Yes, of course, I have now edited that in. Thanks. But in order to mimic an Html.DropDownListFor() you'll also need to select the selected item.
  • Naimish Mungara
    Naimish Mungara over 7 years
    add @Html.NameFor(x=>x.Entity Property) tag can value bind in model..