具有方法的ASP.NET MVC ViewModel-是否“合法"? [英] ASP.NET MVC ViewModel with methods - is it "legal"?

查看:80
本文介绍了具有方法的ASP.NET MVC ViewModel-是否“合法"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否应该将视图模型限制为仅具有属性,而不具有方法?

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 checked.

我完全可以做到这一点:

I could do this entirely in my view:

@Html.RadioButton("radiobuttonName", "The value", (id == Model.PersonId)) 

或者我可以将此逻辑移入视图模型:

or I could move this logic into the viewmodel:

@Html.RadioButton("radiobuttonName", "The value", Model.IsChecked(id)

在视图模型中使用此方法:

using this method in the viewmodel:

    public int PersonId { get;set;}
    public bool IsChecked(int id)
    {
        return (id == PersonId);
    }

是可以这样做吗,还是应该完全在视图中完成,或者以其他方式完成?

Is this OK to do, or should it be done entirely in the view, or in some other way?

推荐答案

您可以在ViewModel中包含方法.如果是每次要计算的单个结果,则建议将评估代码添加到您的Controller中,并将结果存储在ViewModel中,但是如果您需要使用更动态的方法和属性来评估事物无法为您做到这一点,那么在ViewModel中执行此操作就可以了.

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.

在上面的示例中,我建议在ViewModel中执行此操作,因为这样ViewModel会将逻辑包含在一个位置,而不是多次复制并粘贴到您的View中.

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.

这篇关于具有方法的ASP.NET MVC ViewModel-是否“合法"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆