如何在ASP.NET MVC中使用JQuery.Ajax传递多个参数

Ari*_*Ari 2 c# asp.net-mvc jquery asp.net-mvc-2

嗨,大家好,我是JSon的新手,不太清楚如何传递数据.我使用ASP.NET MVC作为我的开发平台.

在视图中:

 $(document).ready(function() {
    $("select#Colors").change(function() {
       var photoCategory = $("#Colors > option:selected").attr("value"); // 1st parameter
       var userID = $(".userID").attr("value"); // 2nd parameter         
       $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "/FindPhotos/" + photoCategory ,
            data: "{}",
            dataType: "json",

            success: function(data) {
            $('#ProductsDiv > div').remove(); 
                if (data.length > 0) {
                    var options = ''; 
                } .......
       });
    });
});
Run Code Online (Sandbox Code Playgroud)

在Global.asax中:

routes.MapRoute(
       "FindPhotos",
       "FindPhotos/{category}",
        new { controller = "Clinical", action = "FindPhotosByCategory", category = "" }
       );
Run Code Online (Sandbox Code Playgroud)

所以一切正常,因为我只在$ .ajax网址中传递一个参数'photoCategory'.我现在的目标是传递第二个参数,即userID,所以我可以在下面的控制器方法中使用它们.

在控制器中:

 public JsonResult FindPhotosByCategory(string category, string userID) {

        List<PhotoSet> photoset = Repository.GetPhotoSetByUserID(userID);

        return new JsonResult
        {
             Data = (from p in photoset 
                     where p.PhotoCategory == category
                     select p).ToArray<PhotoSet>()
        };
    }
Run Code Online (Sandbox Code Playgroud)

有谁知道如何编写$ .ajax()方法,以便我可以将2个参数传递给控制器​​?谢谢!

and*_*ows 5

取决于你想如何传递它.您正在进行GET,但您的路由不支持userId作为路由参数,因此您可以在查询字符串上传递它.URL是/ FindPhotos/lolcats?UserId = 123.

也就是说,您是想让这个人选择用户还是要使用当前登录用户的用户ID.如果是后者,我会争辩说你只是从控制器抓住并保持路线清洁.

本着保持路线清洁的精神,我实际上将路线更改为如下所示:

routes.MapRoute( 
       "FindPhotos", 
       "FindPhotos/{category}/{userId}", 
        new { controller = "Clinical", action = "FindPhotosByCategory", category = "", userId=UrlParameter.Optional } 
       ); 
Run Code Online (Sandbox Code Playgroud)

这将为您提供选项,使userId可选,然后根据是否提供过滤.你的ajax调用然后变成:

   $.ajax({ 
        type: "GET", 
        contentType: "application/json; charset=utf-8", 
        url: "/FindPhotos/" + photoCategory + "/" + userId , 
        data: "{}", 
        dataType: "json", 
Run Code Online (Sandbox Code Playgroud)

最后,它与JSON无关,而与调用URL的方式有关.再次,这是GET所以你可以把它传递给URL并且没问题.

在旁注 - 我确信你知道 - 为了安全起见,我会尽量避免将实际的用户ID放入标记或其他任何地方.如果必须这样做,请确保在代码的业务逻辑/数据访问部分中以某种方式保护访问.