Gyuzal
Gyuzal

Reputation: 1591

Ajax request to controller to get data for DropDownList in asp.net?

I'd appreciate if someone could advise on the following: I invoke my controller ActionResult passing some string and then I get the data. How can I use this data to populate my DropDownList and show it to user?

   $.ajax({
      type: "POST",                            
       url: '@Url.Action("Action","Controller")', 
      data: { passedString: "Industrial"},           
      success: function(data){
           //pass data to ViewBag??
      }
});

my view:

@Html.DropDownListFor(model => model.TraumaCode, (SelectList)ViewBag.TraumaList)

my controller action:

    public ActionResult GetTraumaType(string passedString)
    {
        if (passedString == "Industrial")
        { 
        ViewBag.TraumaList = some Value...
        }
        else
        {
         ViewBag.TraumaList = another Value...
        }
    }

I understand I cannot change the ViewBag info, because the page is loaded once, is there another way to pass data to DropDownList?

Upvotes: 0

Views: 1512

Answers (2)

Roy Dictus
Roy Dictus

Reputation: 33149

Why are you using HTTP POST to get the data from the controller method?

You can change the POST to GET or decorate your controller method with

[HttpPost]

which tells ASP.NET MVC to accept POST requests for that method.

And of course your method must return an ActionResult (a JsonResult if you want to return JSON data) that the AJAX success function can then process.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

You could return it as a JSON result:

public ActionResult GetTraumaType(string passedString)
{
    if (passedString == "Industrial")
    { 
        return Json(some_value, JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(some_other_value, JsonRequestBehavior.AllowGet);
    }
}

and then:

$.ajax({
    type: "POST",                            
    url: '@Url.Action("Action", "Controller")', 
    data: { passedString: "Industrial"},           
    success: function(data) {
        // here you could rebind the ddl:
        var ddl = $('#TraumaCode'); // verify the id of your ddl
        ddl.empty();
        $.each(result, function() {
            ddl.append(
                $('<option/>', {
                    value: this.value,
                    html: this.text
                })
            );
        })
    }
});

Now of course your controller action should return as JSON an array that has the value and text properties. For example:

return Json(new[]
{
    new { value = "1", text = "item 1" },
    new { value = "2", text = "item 2" },
    new { value = "3", text = "item 3" },
    new { value = "4", text = "item 4" },
}, JsonRequestBehavior.AllowGet);

Upvotes: 1

Related Questions