【问题标题】:MVC Redirecting Action using Json使用 Json 的 MVC 重定向操作
【发布时间】:2018-05-29 23:25:21
【问题描述】:

目的:编写的代码是假设使用Json保存所有内容并重定向到操作。

问题: 当前使用 Json 的重定向不允许重定向。 返回新的 JsonResult { Data = new { status = status } };

代码如下供参考:寻找建议:

查看代码

$.ajax({ 
    url: '/SA/Save',
    type: "POST",
    data: JSON.stringify(data),
    dataType: "JSON",
    contentType: "application/json",

    success: function (d) {
        //check is successfully save to database
        if (d.status == true) {
            //will send status from server side
            alert('Successfully done.');

            window.location.href = d.Url;
            //clear form
            t = [];
            d = [];
            r = [];
            $('#SN').val('');
            $('#SA').val('');
            $('#t').empty();
            $('#d').empty();
            $('#r').empty();
        }
        else {
            alert('Failed');
        }
        $('#submit').val('Save');
    },     
});

控制器

public JsonResult Save(SAVM O,)
{
    bool status = false;

    var userId = User.Identity.GetUserId();

    if (ModelState.IsValid)
    {
        SA s = new SA
        {
        }

        _db.SA.Add(O)
        _db.SaveChanges();
        status = true;
    }
    else
    {
        status = false
    }

    return new JsonResult { Data = new { status = status }  };
}

这里想这样重定向:

return RedirectToAction("F", "SA"); 

但使用 JsonResult

解决方案

查看

$.ajax({ 
url: '/SA/Save',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",

success: function (d) {

window.location.href = d.Url;

})
} });

控制器

public JsonResult Save(SAVM O,)

{

var userId = User.Identity.GetUserId();

if (ModelState.IsValid)
{
    SA s = new SA
    {
    }

    _db.SA.Add(O)
    _db.SaveChanges();

 return Json(new { Url = "F/SA" });

}

【问题讨论】:

  • ajax 的全部意义在于保持在同一页面上。如果要重定向,请不要使用 ajax。
  • 是的,可以理解,但如果使用 JsonResult 则有任何建议或解决方法来重定向

标签: c# json ajax asp.net-mvc


【解决方案1】:

这里有几个选项,您可以根据自己的要求决定喜欢哪一个。

  1. 不要使用 AJAX。 AJAX 请求适用于当前页面所需的数据。您应该使用同步请求进行重定向。

  2. success 事件中返回客户端应重定向到的 URL:

    return Json(new { url = "/F/SA" });
    

    然后:

    success: function (d)
    {
        window.location.url = d.url;
    }
    
  3. 返回已经渲染好的View并加载到当前页面:

    return View("some view...");
    

    然后:

    success: function (d)
    {
        $("#someElement").html(d);
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多