0

I've implemented Cascading Drop Down Lists on the Create View page of my MVC Asp.NET Application.

Unfortunately, I am having issues with selecting a value that is located in the JavaScript Array. I need to bind the selected value for the use of one of my controllers.

Right now my List populates, but I have no way to select it. Is there a way to move the counties[i] array from my JavaScript to the @Html.DropDownListFor() helper?

Thanks!

JavaScript:

<script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"
    type="text/javascript"></script>

<script language="javascript" type="text/javascript">
$(document).ready(function() {
    $("#county").prop("disabled", true);
    $("#StateLongName").change(function() {
        if ($("#StateItems").val() != "Please select") {
            var options = {};
            options.url = "/County/GetCounties";
            options.type = "POST";
            options.data = JSON.stringify({ state: $("#StateLongName").val() });
            options.dataType = "json";
            options.contentType = "application/json";
            options.success = function(counties) {
                $("#county").empty();
                for (var i = 0; i < counties.length; i++) {
                    $("#county").append("<option>" +  counties[i] + "</option>");
                }
                $("#county").prop("disabled", false);
            };
            options.error = function() { alert("Error retrieving counties!"); };
            $.ajax(options);
        } else {
            $("#county").empty();
            $("#county").prop("disabled", true);
        }
    });
});
</script>

Controller:

//GET Counties for Cascading Dropdown List
    public JsonResult GetCounties(string state)
    {

        var counties = db.countycigtaxes.Join(db.statecigtaxes,
            cc => cc.stateid,
            sc => sc.stateid,
            (cc, sc) => new
            {
                cc,
                sc
            }).Where(co => co.sc.statefullname == state)
            .Select(co => co.cc.countyfullname).ToList();

        return Json(counties);
    }

View Page:

<div class="form-group">
        @Html.LabelFor(model => model.StateLongName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.StateLongName, Model.StateItems, "Please select")
            @Html.ValidationMessageFor(model => model.StateLongName)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CountyLongName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @*@Html.DropDownListFor(m => m.CountyLongName, )*@
            <select id="county"></select>
            @Html.ValidationMessageFor(model => model.CountyLongName)
        </div>
    </div>

2 Answers 2

1

I assume you mean the the selected value of the property CountyLongName is not posting back when you submit the form. You have commented out this line

@Html.DropDownListFor(m => m.CountyLongName, )

and used

<select id="county"></select>

If you want the manual version (I do not recommend this), then you need to add a name attribute that matches the property name so it can be bound by the ModelBinder

<select name="CountyLongName" id="county"></select>

But it is better to use the helper and pass it an empty SelectList

Html.DropDownListFor(m => m.CountyLongName, Model.CountryNames)

where Model.CountryNames is a property in you view model that is initialised to an empty SelectList

Note also options.type = "POST"; should be "GET" and the whole AJAX could be simplified to

$.get('@Url.Action("GetCounties","Country")', { state: $('#StateLongName').val() }, function(countries) {...

and theToList() is not required in the JsonResult method

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

2 Comments

Thank you! I wasted half a day on this. Also, do you mind telling me why the first suggestion would be considered poor practice?
Using helpers gives you extra benefits including including data attributes for unobtrusive validation, ensuring the html is valid and of course ensuring the name attribute is correct
0

This should set the option selected for you.

$("#county option[value='" + counties[index] + "']").attr("selected", "selected");

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.