简体   繁体   English

如何重定向到动作mvc

[英]How to redirect to action mvc

I am creating an ASP.NET MVC app and I would like it so when an error occurs I call another action which loads a different view. 我正在创建一个ASP.NET MVC应用程序,我希望它在发生错误时我调用另一个加载不同视图的操作。

public ActionResult Invoices()
{
    invoiceClass invoice = getInvoice();
    //do stuff with invoice
}

public invoiceClass getInvoice()
{
    invoiceClass invoice = new invoiceClass();
    try
    {
        // Do stuff
    }
    catch(exception e)
    {
        return RedirectToAction("Index");
    }
    return invoice;
}

I have a method that is very similar to this, when I step through the code, the exception is caught and it hits the redirect call then goes to the return and continues without redirecting. 我有一个非常类似的方法,当我单步执行代码时,异常被捕获并且它命中重定向调用然后转到返回并继续而不重定向。 Am I missing something obvious? 我错过了一些明显的东西吗

If this is an HTTP entry point, you should be returning an ActionResult . 如果这是一个HTTP入口点,您应该返回一个ActionResult

public ActionResult stuff()
{
    try
    {
        // Do stuff
    }
    catch (Exception e)
    {
        //Return a RedirectResult
        return RedirectToAction("Index");
    }

    //Return a JsonResult
    //Example: return the JSON data { "number": 1 }
    return Json(new { number = 1 });
}

Edit 编辑

Here is how I would address your question given the edits you just made. 根据您刚刚编辑的内容,我将如何处理您的问题。

public ActionResult Invoices()
{
    try
    {
        invoiceClass invoice = getInvoice();
        //do stuff with invoice
        return Json(...);
    }
    catch
    {
        //Catch the exception at the top level
        return RedirectToAction("Index");
    }
}

public invoiceClass getInvoice()
{
    invoiceClass invoice = new invoiceClass();
    // Do stuff; possibly throw exception if something goes wrong
    return invoice;
}

you are missing a return 你错过了回归

return RedirectToAction("Index");

And don't forget to change your return type to ActionResult 并且不要忘记将您的返回类型更改为ActionResult

So Ive managed to find a solution to this problem however I'm certain there will be a better more efficient way. 所以我设法找到了解决这个问题的方法,但我确信会有更好的方法。

public ActionResult Invoices()
{
    try{
        invoiceClass invoice = getInvoice();
        //do stuff with invoice
    }catch (exception e){
        return RedirectToAction("Index");
    }
}

public invoiceClass getInvoice()
{
    invoiceClass invoice = new invoiceClass();
    try
    {
        // Do stuff
    }
    catch(exception e)
    {
        index(); //<--the action result
    }
    return invoice;
}

calling index() runs through the method then throws an exception in the Invoices() method which then redirects. 调用index()运行该方法,然后在Invoices()方法中抛出异常,然后重定向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM