Should I try to protect exceptions from exception exceptions / indexes outside of exceptions in MVC views?

I want to post a comment on in this answer: "Have you looked at the abandoned code now? So, what are you going to test?" indicating that it seems to me as soon as you add

<% if (Model.Thing == "abc") {} %> 

or

 @if (Model.Thing == "abc") {} 

In your opinion, there is a potential for something to explode, and this potential must be protected.

Regarding the question I'm connected with, I could see the argument that you should avoid the possibility of eliminating a null reference exception in the code, and not hush up one view with null checks, but what about the case of partial representations? Would it really be better to add a few null checks in numerous places where a partial view can be displayed rather than one place in the view itself?

+3
source share
3 answers

IMO, you should only protect against null, index oob, etc. in your views, if you expect the values ​​to be zero, oob, etc.

Ideally, you should have unit tests for your action methods that ensure that certain model values ​​are non-zero / within /, etc. When it is likely that the value will be zero, you may have a good reason for a zero check in the view. Otherwise, it is useless code.

+2
source

Try to get away from the way you think about Webforms code. Zero checks of model data should be processed in the controller. The view should contain minimal (or not) logic for such a check.

 public ActionResult YourAction(YourModel ym) { if (ym.Thing != null) return View(ym); else return View(); } 

Or any type of validation you should have done with the data. Thus, in your view, it will not be dotted with validation of model data. All of this is part of the separation of concerns in MVC design.

+2
source

If there are no legal conditions under which the model or model properties should be zero, I would say that your unit tests, and not your views, should provide this. If there are cases where the model may be null or contain null properties, then at least check this IF to see if you can customize the mapping. You still need to protect the business logic, as opposed to the display logic (some of which may be related to business rules), seeping into your views.

+1
source

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


All Articles