A viewmodel has a behavior/methods compared to a DTO but

这一生的挚爱 提交于 2019-12-14 03:13:31

问题


People on SO often say:"A ViewModel holds methods that can be executed by the view, properties to indicate how toggle view elements, etc. ..."

When my ViewModel is sent as a WebApi response to the client serialized to JSON, how can this ViewModel execute a method on the client?

This is not clear at all to me.


回答1:


You can understand viewmodel in at least two ways

  • instead of passing your business objects to the view (for example MVC Razor view) you pass stripped down objects that contain properties that are needed for this view and nothing else. View creation is easier and you avoid problems when view designer uses fields that are lazy loaded from database (avoid Select N+1 problem and others)

  • you can create viewmodel that will be used client side (in Javascript). You create it in Javascript as object and thus it can contain methods that view can call. What you are describing (sending JSON objects using WebAPI) is just data that will feed that viewmodel. For example of this you can look on main page here knockoutjs. You can see TicketsViewModel that contains tickets array. In this example you can see three kinds of tickets hardcoded in viewmodel. But you could get them as JSON from WebAPI like you described. After downloading them just put them in this array.




回答2:


A DTO (data transfer object) contains data in a consumable format. A ViewModel/ActionModel contains data formatted for the View to consume.

A DTO might look like:

public class OrderDTO
{
    public decimal Price { get; set; }
    public int Amount { get; set; }
}

While a ViewModel might look like:

public class OrderViewModel
{
    public decimal Price { get; set; }
    public int Amount { get; set; }
    public string PriceBackgroundColor { get; set;}
    public Uri ImageUri { get; set; }
}


来源:https://stackoverflow.com/questions/15097732/a-viewmodel-has-a-behavior-methods-compared-to-a-dto-but

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!