如何从 Jquery 调用 ActionResult

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18050894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:26:19  来源:igfitidea点击:

how to call An ActionResult from Jquery

asp.netasp.net-mvcjqueryasp.net-mvc-4

提问by barak ben horin

this is my ActionResult

这是我的 ActionResult

{          

    UsersModel um = new UsersModel();
    um.Users = userRepository.GetAllUsers();
    um.UserCustomers = userRepository.GetAllUserCustomerConnections();
    um.UserTypes = enums.GetAllDescriptions(CodeType.UserType);
    um.Customers = userRepository.GetAllCustomers();
    um = SearchUsers(Request,um);
    return View(um);
}

it uses the function SearchUsers :

它使用函数 SearchUsers :

    private UsersModel SearchUsers(HttpRequestBase request, UsersModel curModel)
    {
        try
        {
            // request parameters
            string userName = request.Params["user-name"];
            string firstName = request.Params["first-name"];
            string lastName = request.Params["last-name"];
            int status,type,businessId;

            if (!string.IsNullOrWhiteSpace(userName))
                curModel.Users = curModel.Users.Where(u => u.Username.Contains(userName));
            if (!string.IsNullOrWhiteSpace(firstName))
                curModel.Users = curModel.Users.Where(u => u.FirstName.Contains(firstName));
            if (!string.IsNullOrWhiteSpace(lastName))
                curModel.Users = curModel.Users.Where(u => u.LastName.Contains(lastName));
            if (int.TryParse(request.Params["status-search"], out status))
                curModel.Users = curModel.Users.Where(u => u.Status == status);
            if (int.TryParse(request.Params["userTypes-search"], out type))
                curModel.Users = curModel.Users.Where(u => u.UserType == type);
            if (int.TryParse(request.Params["busi-name"], out businessId))
                curModel.Users = curModel.Users.Where(u => u.LastCustomerId == businessId);

            return curModel;
        }
        catch
        {
            return curModel;
        }

    }

now i have on my view a button with the id "search-users" and my command in the js file :

现在我在 js 文件中有一个带有 id“search-users”的按钮和我的命令:

$('#search-users').click(function () { 

    });

how can i post the HttpRequestBase to the controller ?

我如何将 HttpRequestBase 发布到控制器?

回答by Rowan Freeman

I can't answer this fully because I don't know exactly how everything is structured.

我无法完全回答这个问题,因为我不确切知道一切的结构。

Whether the call to your action is using AJAX or not you will still have the same objects during the request. This means that you will still have a Requestobject that is of type HttpRequestBase. This is good news; it means that handling AJAX requests is relatively simple.

无论对您的操作的调用是否使用 AJAX,您在请求期间仍将拥有相同的对象。这意味着您仍将拥有一个Request类型为 的对象HttpRequestBase。这是个好消息;这意味着处理 AJAX 请求相对简单。

Firstly, decide how to handle your action so that it's appropriate for it to be used with AJAX. You can use Request.IsAjaxRequest()to branch your logic.

首先,决定如何处理您的操作,以便它适合与 AJAX 一起使用。你可以Request.IsAjaxRequest()用来分支你的逻辑。

For example:

例如:

{          
    UsersModel um = new UsersModel();
    um.Users = userRepository.GetAllUsers();
    um.UserCustomers = userRepository.GetAllUserCustomerConnections();
    um.UserTypes = enums.GetAllDescriptions(CodeType.UserType);
    um.Customers = userRepository.GetAllCustomers();
    um = SearchUsers(Request,um);
    if (Request.IsAjaxRequest())
    {
        return PartialView(um);
    }
    return View(um);
}

In your view you want your button to

在您看来,您希望您的按钮

  1. Send a request using AJAX
  2. Do something with the response.
  1. 使用 AJAX 发送请求
  2. 对响应做一些事情。

One way to do this might be for your button to send a request to the action and for the action to return a PartialView(as in the example above). This means that you will need to replace the contents of the page with the returned HTML.

执行此操作的一种方法可能是让您的按钮向操作发送请求并让操作返回 a PartialView(如上例所示)。这意味着您需要用返回的 HTML 替换页面的内容。

Your button looks like a good start.

你的按钮看起来是一个好的开始。

You'll need your AJAX script to explain which URL to request, some data to send and what to with the response (at a minimum). Example (non-functional, this is only a guide):

您将需要 AJAX 脚本来解释要请求的 URL、要发送的一些数据以及响应的内容(至少)。示例(非功能性,这只是一个指南):

$('#search-users').click(function () { 
    $.ajax({
        url: "@Url.Action("Index", "MyController")",
        data: {user-name: $("#user-name").val(),
               first-name: $("#first-name").val(),
               last-name: $("#last-name").val()},
        success: function(data) {
                $("#content").html(data);
            };
        }
    );
});

回答by Nirman

$.ajax({
            type: "GET",
            url: @Url.Action('actionname', 'controllername'),
            data: ({ param1: $('ctl').val(),...}),
            success: function (result) {
//do something
            }
        });