Is try catch in a view bad practice? [closed]

2019-04-07 05:38发布

In an MVC3 application, is it considered bad practice to use a try catch block inside of a razor block @{ } in the .cshtml view?

6条回答
我想做一个坏孩纸
2楼-- · 2019-04-07 06:16

Well your use depends on the specifics of your application however you should try to keep your views as bare as possible. Ideally code validity would be verified in the controller and never passed to the view.

查看更多
Emotional °昔
3楼-- · 2019-04-07 06:22

Very much so.

Views should not contain any real logic; anything that might throw an exception belongs in the controller.

查看更多
Ridiculous、
4楼-- · 2019-04-07 06:22

I would say so. The optimal route would to have the Model passed to the View validated by the controller before it reaches the view.

查看更多
干净又极端
5楼-- · 2019-04-07 06:28
@{
try
{
    <td>
        @((TradeType)Enum.Parse(typeof(TradeType), item.AppCode)).GetDescription();
    </td>
}
catch
{
    <td>@item.AppCode
    </td>
}
}
查看更多
▲ chillily
6楼-- · 2019-04-07 06:31

Don't put such code in Views. Views should be only for your display markup as much as possible. You can put that try catch in your controller action method which supplies the data to a view.

public ActionResult GetUser(int id)
{

  try
  {
    //Get the ViewModel and return the correct View.
  }
  catch(Exception ex)
  {
    //log the error
    return View("YourErrorView");
  }   

}

Keep in mind that one of the things MVC emphasizing is separation of concerns. Views should be clean and readable Markup.

查看更多
做个烂人
7楼-- · 2019-04-07 06:34

It is not a good thing to do. The MVC framework is designed to seperate the view with the logic. So keep the logic where it should be, in the controller.

查看更多
登录 后发表回答