Naimish Mungara
Naimish Mungara

Reputation: 237

Bind Mvc Model using with html <select> tag

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...

Upvotes: 3

Views: 19229

Answers (5)

Naimish Mungara
Naimish Mungara

Reputation: 237

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.

Upvotes: 3

Barry Franklin
Barry Franklin

Reputation: 1820

Here's how I would do it:

I would forget the ajax that you're trying to use and use @Ajax.BeginForm and @Html.DropDownListFor.

I'm assuming that you're trying to chain select lists where the user selects a state and it populates the cities in that state.

First you'll need your models, one for the main view and one for the partial we'll need:

MainViewModel:

List<CityData> CityDatas;
Int SelectedCity;
List<StateData> StateDatas;
Int SelectedState;

PartialViewModel:

List<CityData> CityDatas;
Int SelectedCity;

Next you'll need to bind that data from your model in your view (I'm assuming that the state data exists when you first load your main view):

@Ajax.BeginForm("GetCityList", New AjaxOptions() { UpdateTargetId = "CityData", InsertionMode = InsertionMode.Replace, HttpMethod = "Get" })
{
    @Html.DropDownListFor(x => x.SelectedState, new SelectList(Model.StateDatas, "StateId", "State"), new { @class = "form-control", id = "ddlState", onchange = "$(this.form).submit();" })
}
<div id="CityData">
    @Html.Partial("_CityDataPartialView", new PartialViewModel( CityDatas = Model.CityDatas, SelectedCity = Model.SelectedCity))
</div>

Notice how I have the drop down list for cities in a partial view, that is so we can update the drop down using Ajax with an ActionResult in the controller that returns that partial view with a List<CityData> and and Intas it's model:

Public ActionResult GetCityList(int SelectedState) {
    //Get the data for the cities and put it in the model, which is a list of CityData
    List<CityDatas> Data = Context.From.Database.Or.Wherever.Using.SelectedState;
    Int selected = 0; // Here you can pre-select a city if you want
    return ParitalView("_CityDataPartialView", new PartialViewModel( CityDatas = Data, SelectedCity = selected));
}

And then don't forget to create the "_CityDataPartialView" partial view that takes a List<CityData> and an Int as it's model:

@model PartialViewModel
@Html.DropDownListFor(x => x.SelectedCity, new SelectList(Model.CityDatas, "Id", "CityName"), new { @class = "form-control", id = "ddlCity" })

Now when you select a state it will perform an Ajax call to get the cities and update the partial view that contains the drop down list for cities and everything will be bound to the model => states, selected state, cities, selected city.

Remember to send a new List<CityData>()for CityDatas when you first load the model for the main view or it'll give you an error.

Also, you need to have UnobtrusiveJavaScriptEnabled set to true in your web config:

<appSettings>
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

...and also have jquery.unobtrusive-ajax.js referenced... or none of the @Ajax stuff will work.

This has not been tested, but possibly with minor adjustments it will work.

Upvotes: 0

Jaimin Dave
Jaimin Dave

Reputation: 1222

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>

Upvotes: 6

CodeCaster
CodeCaster

Reputation: 151586

If you're certain you want to populate this dropdown using JavaScript, you'll need to pass the model value to JavaScript and test whether it is selected.

So something like this:

var cityId = @Model.CityId;

// ...

        var defaultSelected = cityId == 0;
        var defaultV = new Option("--Select--", 0, defaultSelected);

        // ...

        for (var i = 0; i < cityData.length; i++) {             
            var thisCitySelected = cityData[i].Id == cityId;
            var opt = new Option(cityData[i].CityName, cityData[i].Id, thisCitySelected);
            $('#ddlCity').append(opt);
        }

Apart from that, if you want the binding to work upon sumbitting the containing form, you'll have to give the input element a name:

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

Upvotes: 0

Avinash Vyas
Avinash Vyas

Reputation: 64

Below is the example-

<div class="col-sm-6">
                <div class="form-group formMain required">
                    <label asp-for="CountryId" class="col-sm-4 control-label mandatory"></label>
                    <div class="col-sm-8">
                        <select asp-for="CountryId" asp-items="Model.CountryList"></select> 
                        <span asp-validation-for="CountryId" class="text-danger"></span>
                    </div>
               </div>
            </div>

Where 'CountryList' is being passed from ViewModel property and 'CountryId' is the field used to save value in database table.

Upvotes: 0

Related Questions