【问题标题】:Best Practice: transform model to json viewmodel最佳实践:将模型转换为 json 视图模型
【发布时间】:2014-11-27 12:52:04
【问题描述】:

我将 ASP WebAPI 和 knockoutJS 用于单页应用程序。

现在,我有 webfrontend 和 knockoutJS 视图模型。另外,我有一个 SQL 数据库(模型)。

现在我想将模型数据导入前端。我不知道这样做的最佳方法是什么。 当然,我可以将模型序列化为 JSON。我知道 ko.mapping-plugin 和 Razor 序列化机制。

我的问题是:我的模型与视图模型完全不同。我需要一个转换机制什么的。

示例模型:

  1. 表:国家/地区/列:ID、名称
  2. 表:CitiesInCountry / Cols:ID、名称、CountryID

示例视图模型:

{名称:'德国',城市:['柏林','纽伦堡','科隆']}

所以模型保存了所有可用的国家+城市,前端只显示一个国家及其城市。

不是在寻找算法。我正在寻找“做到这一点的最佳方法”。是控制器的转换部分吗?我需要一个用于视图模型的 c# 类(然后对其进行序列化)吗?

有人可以指点我一个好的设计模式/教程/示例项目吗?

谢谢!

【问题讨论】:

    标签: c# asp.net-mvc mvvm knockout.js asp.net-web-api


    【解决方案1】:

    转换是控制器的一部分吗?我需要一个 c# 类吗 对于视图模型(然后对其进行序列化)?

    是的,你需要用这种方式创建 ViewModel -

    public class CountryViewModel
    {
        public string Name { get; set; }
        public List<string> Cities { get; set; }
    }
    

    然后你将使用这个类来制定实现。然后最后使用 Json 序列化发送。

      [HttpGet]
      public JsonResult GetDate()
      {
          var model = new CountryViewModel();
          // Get data from Database and Initialize/map it to model here or create list<CountryViewModel>
          return Json(model, JsonRequestBehavior.AllowGet);
      }
    

    在客户端使用这种代码 -

     // Get data from server
     var getFilteredData = function () {
         $.ajax({
             type: "GET",
             url: "/URL/GetData",
             contentType: "application/json; charset=utf-8",
             success: function (data) {                            
                      self.KOObservableVariable(data);
             },
             failure: function (errMsg) {
                      alert(errMsg);
             }
         });
     }
    

    【讨论】:

      【解决方案2】:

      在服务器端进行所有转换,只为前端渲染和 UI 事件。 您可以创建一些业务逻辑层,在其中进行所有转换,并且在 web-api 控制器中只返回完整的结果。

      在客户端,它只接收结果并尽可能少地执行操作。

      例子:

      public class DBTable
      {
          public int Id {get; set;}
          public string Param1 {get; set;}
          // and others
      }
      
      public class ViewModelClass
      {
          public string CustomParam1 {get; set;}
          // and so on
      }
      
      //in web-api controller 
      public ViewModelClass GetData()
      {
          return new BLL.Data().GetData();
      }
      
      // in BLL namespace Data class
      public class Data()
      {
          //DAL - data access layer - implement it as you would like. 
          var ViewModelClass result = new DAL.DataDAO().GetData()
              .ConvertAll(x=> new ViewModelClass() { 
                  // do all your transformation here
                  CustomParam1 = x.Param1,
                  // and other
              });    
      }
      

      【讨论】:

      • 具体,这意味着我需要我的 json-viewmodel 的 poco 表示?所以我实现了一个 c#-viewmodel -> 用模型中的数据填充它(包括转换) -> 序列化它 -> 将它发送到前端?
      • @user3796786 添加了一些示例
      • 谢谢,两个答案都是正确的。两者都对我帮助很大!我个人更喜欢另一个答案,所以我选择这个作为正确的答案。
      猜你喜欢
      • 2011-03-06
      • 1970-01-01
      • 2011-09-16
      • 2011-04-08
      • 1970-01-01
      • 2011-06-21
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多