0

c# and jquery,

I have two drop-down lists(category and product), and have to change the product list based on the category.

  @Html.DropDownList("categoryId", new SelectList(ViewBag.Category, "Id", "Name"), "Select Parent Category", new { @class = "form-control categorydata" })      
  @Html.DropDownList("productId", new SelectList(ViewBag.Product, "Id", "Name"), "Select Product", new { @class = "form-control product-list" })      

And i am writing the following controller for getting the products list.It is worked.

    [HttpGet]
    public JsonResult GetProducts(int categoryId)
    {
        int tot = new Products().Total;
        int cont = 1;
        Category cat = new Category(2);
        var products = new Products(cont, tot, cat);
       // ViewBag.products = new Products(1,new Products().Total,new Category(categoryId));
        return Json(products);
    }

and my jquery is,

$('.categorydata').change(function () {
    var selCat = $(".categorydata").val();
    var url = "~/Add/GetProducts";   
    if (selCat.length != 0) {           
        $.get(url, { id: SelCat }, function (data) {
            alert(data);
        });
    }       
});

This jquery is didn't call the controller, and it can not get the data .

Please help me to solve it.

3
  • Instead of "~/Add/GetProducts" Use @Url.Action("ActionName", "Controller") and Also instead of $.get use $.getJSON Commented Oct 27, 2014 at 6:21
  • You should set the dataType to json. Commented Oct 27, 2014 at 6:24
  • Don't you think SelCat should be selCat ?? Commented Oct 27, 2014 at 6:47

3 Answers 3

1

You should keep the property name in json data as same as the parameter name of the action method.

$.get(url, { categoryId : SelCat }, function (data) {

Refer the SO Post.

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

Comments

0

You should use this.

return Json(products,System.Web.Mvc.JsonRequestBehavior.AllowGet);

2 Comments

but jquery never call the controller action
You used the HttpGet Attribute, so you should use JsonRequestBehavior.AllowGet enum.
0

Try to put dataType: 'json' in you ajax call:

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.