0

I want to make two cascade dropdownlists. When the user selects the item in dropdownlist this action fires :

 public SelectList myFunc(string item)
    {
        var query = //Query

        var sItems = new SelectList(query);
        ViewBag.StagesList2 = sItems;
        return ViewBag.StagesList2;
    }

and this my script :

<script>
    var isChanged = false;
    $(function () {
        $('#stageOne').change(function () {
                $.ajax({
                    url: "/Shop/myFunc/",
                    data: { item: $("#stageOne option:selected").text() },
                    type: 'post',
                    success: function () {
                     document.getElementById("stageTwo").options.add(ViewBag.StagesList2);
                 }
            });

        });
    });
</script>

The action fires successfully. But in nothing add to my second dropdownlistfor :

    <div class="drop-down-list">
        <%: Html.DropDownListFor(model => model.StageId, Enumerable.Empty<SelectListItem>(),new { id="stageTwo"})%>
        <%: Html.ValidationMessageFor(model => model.StageId) %>
    </div>

What is the problem??

tereško
  • 58,060
  • 25
  • 98
  • 150
Angelina
  • 103
  • 4
  • 10

1 Answers1

0

You can only use the viewbag when a page is being constructed. Once the browser is displaying the page, there is no more viewbag. Suppose you do the following:

ViewBag.MyName = "John Doe";

And when your page is loaded:

<h2>Welcome, <%: ViewBag.MyName %> ! </h2>

The only thing the browser sees is:

<h2>Welcome, John Doe ! </h2>

The browser has no idea how the page was constructed. It doesn't know about a Viewbag, because that's an ASP.NET feature, it has nothing to do with the browser.

What you need to do is pass the StagesList2 data in a return statement, then process that data in the success callback of the ajax call.

So your code would become something like this:

public JsonResult myFunc(string item)
{
    var query = //Query, let's assume this passes a list of items with an ID and a Name field.


    return Json(query, JsonRequestBehavior.AllowGet); //This sends your query result back as a JSON object
}

Then your Ajax's success callback would be:

success: function (myJSONdata) {
    //first, clear the current contents
    $("#stageTwo").html("");

    //Now proces the new items piece by piece        
    var items = myJSONdata.items;

    for(var i=0; i < items.length; i++) {
        var item = items[i];
        var optionhtml = '<option value="' + item.ID + '">' + item.Name + '</option>';

        $("#stageTwo").append(optionhtml); //Appends the above option to the selectlist
    }

    //Done!
    alert("Everything is now correctly processed!");
}

You'l have to check the names of the fields, I just used some examples, but I hope you get the general idea of how to process the data :)

Feel free to ask if it's not clear enough.

Flater
  • 12,908
  • 4
  • 39
  • 62