简体   繁体   中英

How to access controller action result in Jquery?

I am writing a code for multilevel menu. Main menu ie first level menu is loadedin page load. Upon clicking the item in the main menu sublevel menu are created. Items in the sulevel menu is created by action result in controller. Since it is n level submenu I am using jquery to populate submenu.

Following is the code of main menu, which is a simple list

    <ul>
    <li><a href="#" >item1</a>
    <li><a href="#">item2</a> </li>
    <li><a href="#">item3</a></li>
    <li><a href="#">item4 </a></li>
    </ul>

Following is the action result of a controller which returns the subitems of menu item given it's ID.

     public PartialViewResult SubItems(int id)
    {

            MyQueries obj = new MyQueries();
            ViewData["SubCategories"] = obj.getChildCategories(id);
            ViewData["Services"] = obj.getServices(id);
            return PartialView();


    }

I hope above details gives u an idea, I want to write a jquery code, a click event for anchor.. which receives the parameter that is item text and uses the controller and creates submenu. For example user clicks on item1, jquery code should send 'item1' id to a controller which returns child items.. then code should create UL lI list which has subitems. I hope I made it clear

I would use jquery ajax to perform a get request, and be sure to specify what datatype it accepts from the server:

$('#anchorid').click(function() {
var returnData = $.ajax({ url: @Url.Action("subitems"),
type: "GET",
dataType: "json",
data: {"id": this.attr("id"),
});
//TODO:  build your list using returnData object

});

This code is far from perfect, but should give you an idea on how to use Ajax to return a request. Note that if you're going to use this technique, you shouldn't be returning a partial view on the server, you should be returning whatever object type the AJAX is expecting. Heres the reference material for the jQuery AJAX request: http://api.jquery.com/jQuery.ajax/

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