【发布时间】:2015-10-31 16:17:08
【问题描述】:
在控制器的动作被重定向到同一个控制器的另一个动作。结果:“HTTP 错误 404.0 - 未找到”。 GetData 通过 JQuery 中的 ajax-request 调用。重定向时请求 url http://localhost:61327/Home/Index/qwertyQWERTY%20HTTP/1.1。请求地址http://localhost:61327/Home/Index/qwertyQWERTY 工作正常。控制器、ajax-request 和 RouteConfig.cs 的代码如下所示。
路线
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{d}",
defaults: new { controller = "Home", action = "Index", d = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default1",
url: "{controller}/{action}/{data}",
defaults: new { controller = "Home", action = "GetData", data = UrlParameter.Optional }
);
}
家庭控制器
public ActionResult Index(string d)
{
Repository repository = new Repository();
ViewBag.ViewbagValues = repository.GetAllCustomersAndOrders();
Response.Write("Ku-ku");
Response.Write(d);
return View(repository.GetAllCustomersAndOrders());
}
[HttpPost]
[ValidateInput(false)]
public ActionResult GetData(string data)
{
Response.Write(Request.InputStream);
Response.Write("qwerty");
return RedirectToAction("Index", "Home", new {d="qwertyQWERTY"});
}
脚本
function SendDataToController(data) {
$.ajax({
url: "Home/GetData",
type: "POST",
datatype: "text",
contentType: "application/text; charset=utf-8",
data: data,
success: function (result) {
alert("Data was send to the controller");
window.location = result.URL;
},
error: function (err) {
alert("Error: data was not send to the controller");
}
});
alert(data);
【问题讨论】:
-
您正在进行 ajax 调用。 Ajax 调用不会重定向(ajax 的全部意义在于保持在同一页面上)。在您的成功回调中,结果是一个视图 (html),它不包含名为
URL的属性,因此它未定义。如果你想重定向,不要使用ajax。 -
但重定向不在 ajax-request 中执行。它执行了行动。还是原来使用ajax的事实?
-
Ajax 调用不要重定向。它将响应返回到同一页面。如果你想重定向,使用 ajax 是没有意义的 - 只需进行正常提交即可。
-
能否在“$.ajax()”中设置“async: false”来解决问题?
-
没有。你想做的是什么?如果您想重定向,请不要使用 ajax - 它毫无意义。
标签: asp.net asp.net-mvc