如何在asp.net mvc中使用TemData[]来处理错误?

时间:2022-11-29 13:58:46

I want to handle following errors using TempData:

我想用TempData处理以下错误:

1) My custom Error defined by me if certain condition is not fulfilled.

1)如果某些条件没有实现,我定义的自定义错误。

2) To display the exact SQL-server error.

2)显示准确的SQL-server错误。

Note: I am Using Redirect after the code.

注意:我在代码后使用重定向。

1 个解决方案

#1


0  

May be you need like this: In the controller

也许你需要这样:在控制器中?

public ActionResult SaveProduct(Product model)
   {
      var ErrorString = null;

      // your custom validations for example,
      if(model.Name == null) ErrorString = "Name is empty";

      try
      {
         // your db save operations 
      }
      catch (Exception exception)
      {
         ErrorString = exception.Message;
      }

      if(ErrorString != null) TempData["Error"] = ErrorString;
      return Redirect("YourAction"); 
    }

And in View:

和观点:

@{
    var error = (string)TempData["Error"];
}


@if (!string.IsNullOrEmpty(error))
    {
       <p>@Html.Raw(error)</p>
    }

#1


0  

May be you need like this: In the controller

也许你需要这样:在控制器中?

public ActionResult SaveProduct(Product model)
   {
      var ErrorString = null;

      // your custom validations for example,
      if(model.Name == null) ErrorString = "Name is empty";

      try
      {
         // your db save operations 
      }
      catch (Exception exception)
      {
         ErrorString = exception.Message;
      }

      if(ErrorString != null) TempData["Error"] = ErrorString;
      return Redirect("YourAction"); 
    }

And in View:

和观点:

@{
    var error = (string)TempData["Error"];
}


@if (!string.IsNullOrEmpty(error))
    {
       <p>@Html.Raw(error)</p>
    }