Is trying to catch bad practice in mind?

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

+6
source share
6 answers

Highly.

Views should not contain any real logic; everything that can throw an exception belongs to the controller.

+12
source

It’s good that your use depends on the specifics of your application, but you should try to keep your views as smooth as possible. Ideally, the validity of the code will be checked in the controller and will never be passed to the view.

+2
source

Do not put such code in views. Views should only be for your display layout as much as possible. You can put this try catch in your controller action method, which passes data to the 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 that MVC emphasizes is the separation of concerns. Presentations should be clean and readable. Markup.

+2
source

I would say so. The optimal route would be for the model to be passed to the view, verified by the controller, before it reaches the view.

+1
source
 @{ try { <td> @((TradeType)Enum.Parse(typeof(TradeType), item.AppCode)).GetDescription(); </td> } catch { <td>@item.AppCode </td> } } 
+1
source

This is not good. The MVC structure is designed to separate a view using logic. Therefore, keep the logic where it should be in the controller.

0
source

Source: https://habr.com/ru/post/911535/


All Articles