在视图中显示异常错误消息

时间:2016-03-18 08:02:11

标签: c# asp.net-mvc exception exception-handling

我试图像这样获取异常消息并在控制器类中传递给FileUpload这样的视图

        catch (Exception ex)
        {
            ViewBag.Error = ex.Message;                
        }

        return RedirectToAction("FileUpload", "FileUpload",ViewBag.Error);
    }

FileUpload视图页面中,我试图显示此错误信息

@ViewBag.Error

但我在这里看不到任何错误消息

修改

    [HttpGet]
    public ActionResult FileUpload()
    {
       ..
       return View(p);
    }

    [HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase file)
    {
        ..
        return RedirectToAction("FileUpload", "FileUpload");
    }

2 个答案:

答案 0 :(得分:1)

您需要在 FileUpload 操作中接受该消息,然后再将其分配给viewbag以获取页面中的数据。

   string exmsg="";
    try
    {
    //....
    }
    catch (Exception ex)
    {
     exmsg = ex.Message;                
    }
    return RedirectToAction("FileUpload", "Controllername", new { errormsg = exmsg });
    }

[HttpGet]
    public ActionResult FileUpload(string errormsg)
    {
       ViewBag.Error=errormsg
       return View(p);
    }

答案 1 :(得分:1)

试试这个:

catch (Exception ex)
            {
                return RedirectToAction("FileUpload", "FileUpload", new { errorMessage = ex.Message});                
            }

和Get方法

[HttpGet]
public ActionResult FileUpload(string errorMessage)
{
   @ViewBag.Error = errorMessage;
   . . .
   return View(p);
}

我相信RedirectToAction("FileUpload","FileUpload")的第二个参数是你的控制器名称。