1

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.

1
  • if one of these answers solved your problem you should close it. Thanks. Commented Feb 9, 2011 at 13:46

6 Answers 6

2
$("#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)
Sign up to request clarification or add additional context in comments.

2 Comments

I have changed the script and controller action as you said. But still am not recieving any hit in the breakpoint put in controller action. Do i need to change my view??
Yes, if you're using MVC2. Phil Haack says:"...you only send JSON in response to a POST request..." (haacked.com/archive/2009/06/25/json-hijacking.aspx). So you have to tell jQuery to do a POST and don't forget to use this JsonRequestBehavior.DenyGet when returning JSON.
2

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.

1 Comment

Thanks for the reply. But I need to do it using JQuery scripts. Since external controls are not appreciated in this application.
1

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

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

5 Comments

Thats my mistake. Thanks.. But the ajax part is not functioning. I am not able to get the action in the controller.
Can you see any outgoing AJAX request at all?
I tried in a different way by using jquery.cascadingDropDown.js file. I think this works fine. But I have an issue with not getting the value of tradertype at controller side. $(document).ready(function() { //alert($("#TraderType").val()); $("#Trader").CascadingDropDown("#TraderType", '/Build/ListTraders'); });
@vandalo: Thanks for the responces but my issue is not solved yet. I am not able to get the value of trdrTypeId in the controller. Its always null. I tried with a static value in the controller function and tried to return a list of traders but I couldn't also get that list in the jquery script.
@Suja, I've added another answer with some code. it works here. Try it and let me know.
1

suja,

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

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

hope this helps..

Comments

1

@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));
  }

Comments

0

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.

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.