ASP.NET MVC ViewModel with methods - is it “legal”?

前端 未结 2 1167
时光取名叫无心
时光取名叫无心 2021-02-12 07:04

Should viewmodels be limited to only have properties, and not methods?

Let\'s say I have a radio button in my view, and wants to see if the radio button should be checke

2条回答
  •  轮回少年
    2021-02-12 07:38

    You can have methods in your ViewModel. If it's a single result you want to calculate each time then I'd suggest adding the evaluation code to your Controller and storing the result in the ViewModel instead but if you need to evaluate things using a method more dynamically and a Property can't do this for you then doing this in the ViewModel is probably fine.

    In your example above I'd recommend doing this in the ViewModel as then the ViewModel contains the logic in a single place rather than doing this many times copy and pasted in your View.

提交回复
热议问题