简体   繁体   中英

MVC ajax dropdownlist url change

I am new in ajax and I need a help. This is a script that populates second dropdownlist once first is selected. It works fine using GetStates action that gets data from database.

<script type="text/javascript">
$(document).ready(function () {
    $("#CountriyID").change(function () {
        var abbr = $("#CountriyID").val();

        $.ajax({
            url: "/SetUp/GetStates",
            data: { countryCode: abbr },
            dataType: "json",
            type: "POST",
            error: function () {
                alert("An error occurred.");
            },
            success: function (data) {
                var items = "";
                $.each(data, function (i, item) {
                    items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
                });

                $("#StateID").html(items);
            }
        });
    });
});

</script>

Here is the view that I am working on

@using (Html.BeginForm("Index", "SetUp", FormMethod.Post))
{
    <form action="" method="post">
        <input type="submit" name="action:AddCity" value="Add" />
    </form>
    <div class="editor-field">@Html.DropDownListFor(model => model.CountriyID, new SelectList(Model.Countries, "ID", "Text"))</div>
     <div class="editor-field">@Html.DropDownListFor(model => model.StateID, new SelectList(Model.States, "ID", "Text"))</div>
}

If I need to add a City I click on a submit button and it goes to correct action. The problem happened when I populate dropdownlist. After population, the City button do not respond anymore. It looks like the url get stack at "/SetUp/GetStates" and I cannot do any actions anymore on my form.

Please Let me know what am I doing wrong and where to take a look? Thanks in advance.

try the below code hope it helps you:

<form action="" method="post">

    <div class="editor-field">@Html.DropDownListFor(model => model.CountriyID, new SelectList(Model.Countries, "ID", "Text"))</div>
     <div class="editor-field">@Html.DropDownListFor(model => model.StateID, new SelectList(Model.States, "ID", "Text"))</div>

<input type="submit" name="action:AddCity" value="Add" />
    </form>

As the drop down must come into the tags and submit must be at the last place in the tags ideally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM