加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

如何将我的模型数据(列表)映射到另一个viewmodel数据(列表)MVC a

发布时间:2020-12-16 03:24:14 所属栏目:asp.Net 来源:网络整理
导读:在这种情况下,如何将我的模型数据(列表)映射到另一个viewmodel数据(列表)? 这是我有的: 我的json viewmodel public class JsonViewModel{ public ListJsonItem Items { get; set; } }public class JsonItem{ public string Name { get; set; } public int
在这种情况下,如何将我的模型数据(列表)映射到另一个viewmodel数据(列表)?

这是我有的:

我的json viewmodel

public class JsonViewModel
{
    public List<JsonItem> Items { get; set; } 
}

public class JsonItem
{
    public string Name { get; set; }
    public int Unit { get; set; }
    public decimal Price { get; set; }
    public IEnumerable<Item> ItemStock { get; set; } 
}

我的主要模特

public class Item
{
    public int ItemId { get; set; }
    public string Name { get; set; }
    public int QuantityInPack { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public bool IsHidden { get; set; }
}

应该以这种方式映射:

> Item.QuantityInPack = JsonItem.Unit
> Item.Price = JsonItem.Price

其中Item.Name = JsonItem.Name

调节器

public ActionResult Index()
{
    // 1. Perform HTTP request to retrieve the JSON.
    var webClient = new WebClient();
    string rawJson = webClient.DownloadString("http://my_json_data");

    // 2. Parse the JSON.
    var jsonRootObject = JsonConvert.DeserializeObject<JsonViewModel>(rawJson);

    // 3. Map to viewmodel
    var viewModel = new JsonViewModel
    {
        Items = jsonRootObject.Items.Select(i => new JsonItem
        {
            Name = i.Name,Unit = i.Unit,Price = i.Price
        }).ToList()
    };



    /// var TestItem = db.Items.ToList();
    /// TestItem.QuantityInPack = JsonItem.Unit
    /// TestItem.Price = JsonItem.Price
    ///     where Item.Name = JsonItem.Name
    ///
    /// (I know it's a bad,but I wanted to explain what I mean)
    /// Here i should map data in some way
    /// 
    ///

    // 4. Return mapped model to view
    return View( TestItem??? );
}

解决方法

如果我理解正确,您希望将JsonViewModel与主模型同步并返回同步的主模型以查看:

public ActionResult Index()
{
    ...
    var itemList = db.Items.ToList();
    if (jsonRootObject.Items != null)
    {
        jsonRootObject.Items.ForEach(i =>
        {
            var item = itemList.FirstOrDefault(p => p.Name = i.Name);
            if (item != null)
            {
                item.QuantityInPack = i.Unit;
                item.Price = i.Price;
            }
        });
    }
    return View(itemList);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读