【问题标题】:Alternative to window.location.href using POST request - ASP.NET MVC使用 POST 请求替代 window.location.href - ASP.NET MVC
【发布时间】:2021-09-27 18:18:51
【问题描述】:

我正在用 Javascript 编写下面的代码来检索评论并在重新填充数据后导航同一页面

function MoveItem() {

var empId = document.getElementById('EMP_ID').value;
var commentValue = $("#RESPONSE").val();
if ($.trim(commentToSave).length > 0) {
    showAjaxLoading();
    var empData= "APPROVE";
    var baseControllerUrl = '/Employee/EmpManagement/PushItem';
    window.location.href = baseControllerUrl + "/" + empId + "?comment=" + commentValue + "&empData=" + empData + "&currentItem=" + itemData;

} else {
    aet('Pelase enter comments', 'E');
  }
}

在控制器中方法写成

    [HttpGet]
    public async Task<ActionResult> MoveItem(int id, string comment, string decision, string currentworkflow)
    {
        return RedirectToAction("EditEmpManagemnt", "EmpManagement", new { id = id });
   }

我想将 MoveItem 操作方法转换为 [HttpPost] 类型,在 Javascript 和操作方法中需要进行哪些更改?谁能用示例代码解释一下。

【问题讨论】:

    标签: javascript c# .net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    您可以使用fetch 方法发送POST 请求。我们以 JSON 格式发送数据。用这个替换你的javascript:

    function MoveItem() {
        var empId = document.getElementById('EMP_ID').value;
        var commentValue = $("#RESPONSE").val();
        if ($.trim(commentToSave).length > 0) {
            showAjaxLoading();
            var empData = "APPROVE";
            var baseControllerUrl = '/Employee/EmpManagement/PushItem';
    
            var url = baseControllerUrl + "/" + empId;
    
            //here we put the url as a first parameter
            //then we configure the http method
            //and in the body we pass in the object in JSON format
            fetch(url, {
                method: "POST",
                body: JSON.stringify({
                    "comment": commentValue,
                    "empData": empData,
                    "currentItem": itemData
                })
            }).then(result => {
                //do something with the result you get back
                console.log("Completed with result: " + result);
            }).catch(err => {
                //if any error occured, then show it here
                console.log("There is an error: " + err);
            });
            
        } else {
            aet('Please enter comments', 'E');
        }
    }
    

    在您的 C# 代码中,只需将 [HttpGet] 属性替换为 [HttpPost]

    【讨论】:

    • @Costa..你有没有看到在控制器方法中它使用 RedirectoAction...它是否会使用上面的代码正常工作?因为它正在重新填充数据
    猜你喜欢
    • 2018-07-30
    • 1970-01-01
    • 2016-08-12
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多