c# - MVC Controller 的方法不返回 View

标签 c# ajax asp.net-mvc

我尝试了很多方法,但仍然无法正常工作...我正在使用 ajax 调用来调用 Controller 的方法。由于回答了我之前的问题,它工作正常,我有我想从 Controller 中的 View 发送的数据(在 CreateIncident 方法中)。问题是 Controller 应该呈现新 View 并重定向到它,但它没有发生。现在我只想看到新的 View ,没有别的,我稍后会处理收到的数据。知道为什么会这样吗?这是因为我正在使用 ajax 调用方法而不是通过例如简单 Url.AcionLink?

Ajax 调用方法:

function addMarker(location, fulladdress) {

        var data = JSON.stringify(fulladdress) + JSON.stringify(location)

        $.ajax({
            type: "POST",
            url: "Incidents/CreateIncident",
            dataType: "text",
            data:  {JsonStr : data} 
        })
    }

Controller :

    public ActionResult Create()
    {
        Incident newIncident = new Incident();
        newIncident.AddDate = DateTime.Today.Date;
        newIncident.DateOfIncident = DateTime.Today.Date;
        newIncident.TimeOfIncident = DateTime.Today.TimeOfDay;

        return this.View(newIncident);
    }

    [HttpPost]
    public ActionResult CreateIncident(string JsonStr)
    {

   //   RedirectToAction("Create"); //none of this three is working
   //   return View("Create");
        return Redirect("Create");
    }

无论我是尝试访问 CreateIncident 还是 Create 方法都会被调用,但是没有重定向到/Incidents/Create(我是从 Home 调用/指数)。任何想法为什么?我想直接从 CreateIncident 重定向到 Create.cshtml,这样我就不必在方法之间传递数据,但任何解决方案都可以。

最佳答案

这种情况下的重定向必须通过 AJAX 调用来完成。调用您的操作方法并执行您的逻辑,然后在成功时重定向。

$.ajax({
 type: "POST",
 url: "Incidents/CreateIncident",
 dataType: "text",
 data:  {JsonStr : data} ,
 success: function (data) {
 window.location.href = "Incidents/Create";
 }
})

关于c# - MVC Controller 的方法不返回 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34640387/

相关文章:

c# - 如何获取类型成员的源文件名和行号?

c# - 在Simple injector中注册Decorator,通用接口(interface)

c# - .NET Micro Framework 不安全代码

ASP.NET MVC : How to call custom Html Helper from a controller method?

javascript - 使用 javascript 执行 ajax 调用时阻止用户交互

c# - Ajax 脚本管理器阻止了 jquery?

javascript - 如何将 anchor 标记的 data-id 值传递给 Codeigniter Controller 函数并在数据模型中显示结果?

javascript - 使用 ajax 的 URL 的奇怪行为

javascript - 递归地进行多个 AJAX 调用是一个坏主意

javascript - Gmap 在 js 上无法正常工作