简体   繁体   中英

Cascading dropdown using asp.net mvc

I have a dropdown for tradertype which on selection should populate the dropdown for traders. My view looks like :

`<ul>
                <li>
                    <label>
                        <span class="mandatory">*</span>Trader Type:</label>
                    <%=Html.DropDownList("TraderType", (SelectList)ViewData["TraderType"])%>
                    <%--<select id="ddlTraderType" name="TraderType">
                        <%foreach (SelectListItem item in (SelectList)ViewData["TraderType"])
                          { %>
                        <option value="<%=item.Value %>">
                            <%=item.Text %></option>
                        <%} %>
                    </select>--%>
                    <span class="tagline">Select a Trader type from here<strong></strong></span></li>
                <li>
                    <label>
                        <span class="mandatory">*</span>Trader:</label>
                    <select name="Trader" id="Trader">
                    </select>
                    <span class="tagline">Select a Trader from here<strong></strong></span></li>
</ul>`

I tried using JQuery, but I couldn't get the change event of the 'TraderType' dropdown. My script is:

$("TraderType").change(function() {
        alert("Change");
        $.ajax({ url: $("#ListTraders").attr("action"),
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            cache: false,
            data: { part: $("#TraderType").val() },
            dataType: 'json',
            async: false,
            success: function(data) {
            if ((data.lstTraders.length) > 0) {
                    for (var count = 0; count < data.lstTraders.length; count++) {
                        $("#Trader").append("<option value='" + data.lstTraders[count].Id.toString() + "'>" +
                            data.lstTraders[count].TraderName + "</option>");
                    }
                }
            }
        });
    });

The code in the controller is:

public JsonResult ListTraders(string trdrTypeId)
    {

        IList<HSTrader> lstTraders = new List<HSTrader>();
        Build objBld = new Build();
        Document objDoc = new Document();

        string message = string.Empty;
        bool result = true;
        try
        {
            int trdrType = Convert.ToInt32(trdrTypeId);
            lstTraders = objBld.GetTradersByTrdrTypeId(trdrType);
        }
        catch (Exception ex)
        {
            message = ex.Message;
            result = false;
        }
        return Json(new { Success = result, Message = message, lstTraders = lstTraders });}

Please help me on this.

I recommend you use the controls here;

http://awesome.codeplex.com/

demo: http://demo.aspnetawesome.com/AjaxDropdownDemo

The Ajax Dropdown control can easily be used for cascading dropdowns.

Plus there are lots of other useful controls here as well.

$("#TraderType").change(function() {

});

you're missing # As for the action in your controller try and change the VERB in POST

  $.ajax({ url: $("#ListTraders").attr("action"),
        type: 'POST',

Change your controller like this:

[HttpPost]
public JsonResult ListTraders(string trdrTypeId)

... and when you return JSON you should change this:

return Json(new { Success = result, Message = message, lstTraders = lstTraders }, JsonRequestBehavior.DenyGet);

Another thing, this parameters must match

data: { trdrTypeId: $("#TraderType").val() },

public JsonResult ListTraders(string trdrTypeId)

Isn't the jQuery syntax wrong? Try adding a hash before the ID of the element:

$("#TraderType").change(function...

suja,

make sure your trader click is inside the live event (and also inside the document ready event) ie:

<script type="text/javascript">
    $(document).ready(function() {
        $("#TraderType").live('change', function() {...});
    });
</script>

hope this helps..

@Suja: this is what I've done and it works. I've removed this line too => contentType: "application/json; charset=utf-8",

HTML :

<ul>
    <li>
        <label>
            <span class="mandatory">*</span>Trader Type:</label>
        <%=Html.DropDownList("TraderType", (SelectList)ViewData["TraderType"])%>
        <span class="tagline">Select a Trader type from here<strong></strong></span>
    </li>
    <li>
        <label>
            <span class="mandatory">*</span>Trader:</label>
        <select name="Trader" id="Trader"></select>
        <span class="tagline">Select a Trader from here<strong></strong></span>
   </li>
</ul>

Javascript :

<script type="text/javascript">
$(document).ready(function() {
    $("#TraderType").change(function() {
        $.ajax({
            url: '<%=Url.Action("ListTraders", "Test001")%>',   // MY SAMPLE
            type: 'POST',           
            // contentType: "application/json; charset=utf-8",
            cache: false,
            data: { trdrTypeId: $("#TraderType").val() },
            dataType: 'json',
            async: false,
            success: function(data) {
                if ((data.lstTraders.length) > 0) {
                    for (var count = 0; count < data.lstTraders.length; count++) {
                        $("#Trader").append("<option value='" + data.lstTraders[count].Id.toString() + "'>" +
                            data.lstTraders[count].TraderName + "</option>");
                    }
                }
            }
        });
    });
});
</script>

C#

[HttpPost]
public JsonResult ListTraders(string trdrTypeId)
  {
  return (Json(true, JsonRequestBehavior.DenyGet));
  }

1.

 <%:Html.DropDownList("SubDepartment", (SelectList)ViewData["SelectListSubDepartment"], new { id = "SubDepartment", @class = "combobox" })%>

Supply the default list if any.

2. Create a javascript function

 <script type="text/javascript">
        function onddlChange() {
            $.ajax({
                contentType : 'application/json; charset= utf-8',
                dataType: 'json',
                type : 'POST',
                url : "/ControllerName/IndexChk",
                success : function(data){
                    var markup = '';
                    for (var x = 0; x < data.length; x++) {
                        markup += "<option value='" + data[x].Value + "'>" + data[x].Text + "</option>";
                    }
                    $('#SubDepartment').html(markup).show();
                },
                error: function(ret){
                    alert(ret);
                }

            });
        }
    </script>

3. Now provide the list from the Controller action method.

public JsonResult IndexChk(string selectedvalue = null)
    {
        List<Sbu> departmentList = new List<Sbu>()
        {
            new Sbu { Id = 1, Name="SubPublishing"},
            new Sbu { Id = 2, Name="SubSoftware"},
            new Sbu { Id = 3, Name="SubEngineering"},
            new Sbu { Id = 4, Name="SubShipping"},
            new Sbu { Id = 5, Name="SubTranscription"}
        };
        var selectList = new SelectList(departmentList, "id", "name", selectedvalue);
        return Json(selectList, JsonRequestBehavior.AllowGet);
    }

That's it, Now call created javascript function on any event such on onclick, onchange.

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