In an MVC3 application, is it considered bad practice to use a try catch block inside of a razor block @{ }
in the .cshtml
view?
问题:
回答1:
Very much so.
Views should not contain any real logic; anything that might throw an exception belongs in the controller.
回答2:
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.
回答3:
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.
回答4:
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:
@{
try
{
<td>
@((TradeType)Enum.Parse(typeof(TradeType), item.AppCode)).GetDescription();
</td>
}
catch
{
<td>@item.AppCode
</td>
}
}
回答6:
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.