MVC控制器的方法不返回视图 [英] MVC controller's method not returning view

查看:349
本文介绍了MVC控制器的方法不返回视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried many ways and it's still not working... I'm calling controller's method with ajax call. Thanks to answer to my previous question it's working fine, I have data that I wanted to send from view in controller (in CreateIncident method). Problem is that controller should render new view and redirect to it, but it's not happening. For now I just want to see new view, nothing else, I'll deal with recieved data later. Any idea why is this happening? Is this because I'm calling method with ajax and not by e.g. simple Url.AcionLink?

对方法的Ajax调用:

Ajax call to method:

function addMarker(location, fulladdress) {

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

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

控制器:

    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/Index进行调用).有什么想法吗?我想直接从CreateIncident重定向到Create.cshtml,这样我就不必在方法之间传递数据,但是任何解决方案都可以.

No matter if I'm trying to access CreateIncident or Create the method is called, but there's no redirect to /Incidents/Create (I'm calling from Home/Index). Any ideas why? I would like to redirect to Create.cshtml straight from CreateIncident so I wouldn't have to pass data between methods, but any solution will do fine.

推荐答案

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

The redirect in that case has to be done through you AJAX call. Call your action method and do your logic, then redirect on success.

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

这篇关于MVC控制器的方法不返回视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆