是否可以合并2个视图模型,每个视图模型填充2个不同的LINQ查询并返回1个视图?

时间:2018-08-17 18:38:55

标签: c# asp.net-mvc entity-framework linq asp.net-mvc-viewmodel

我试图在1个视图中显示2组数据:

第一个LINQ:

var result = from add in db.Addresses
                     join u in db.Users on add.UserID equals u.Id
                     where CurrUser == add.UserID
                     select new AddressViewModel
                     {
                        FirstAddressLine = add.FirstAddressLine,
                        SecondAddressLine = add.SecondAddressLine,
                        Town = add.Town,
                        PostCode = add.PostCode,
                        Distance = addDis
                     };

第二个LINQ:

var result = from c in db.Carts
                     join s in db.Sweets on c.SweetID equals s.SweetID
                     where c.CartID == cartId
                     select new ShoppingCartViewModel
                     {
                         SweetName = s.SweetName,
                         Qty = c.Qty,
                         Price = s.Price,
                         SweetTotal = (s.Price * c.Qty),
                         Singular = s.Singular,
                         CartTotal = cartTotal
                     };

2个视图模型如下:

public class AddressViewModel
{
    public string FirstAddressLine { get; set; }
    public string SecondAddressLine { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string PostCode { get; set; }
    public decimal Distance { get; set; } 
}

public class ShoppingCartViewModel
{
    public decimal? CartTotal { get; set; }
    public decimal? SweetTotal { get; set; }
    public bool? Singular { get; set; }              
    public decimal? Price { get; set; }
    public int? RecordID { get; set; }
    public string CartID { get; set; }
    public int? SweetID { get; set; }
    public int? PemixID { get; set; }
    public int? Qty { get; set; }
    public System.DateTime? DateCreated { get; set; }
    public string SweetName { get; set; }
}

但是我不确定将2个视图模型返回1个最佳实践是什么?

编辑:如果我错过了显而易见的内容(仍在学习中),则表示歉意,但是我不确定如何遵循您的答案...我创建了购物车的部分视图: _ShoppingCartPartial 已放置在共享视图文件夹中。

当我尝试在Checkout视图中呈现部分视图时,收到了我期望 ShoppingCartViewModel 的错误,但是我当前正在向其发送 AddressViewModel

我已经为两者做了一个视图模型:

 public class CheckoutViewModel
{
    public IEnumerable<Address> AVM { get; set; }
    public IEnumerable<Cart> SCVM { get; set; }
}

问题是我不确定我应该将控制器(如下)更改为:

public ActionResult Index()
    {
        var CurrUser = User.Identity.GetUserId();
        var addDis = getAddDis(CurrUser);

        var result = from add in db.Addresses
                     join u in db.Users on add.UserID equals u.Id
                     where CurrUser == add.UserID
                     select new AddressViewModel
                     {
                        FirstAddressLine = add.FirstAddressLine,
                        SecondAddressLine = add.SecondAddressLine,
                        Town = add.Town,
                        PostCode = add.PostCode,
                        Distance = addDis
                     };


        return View(result);
    }

3 个答案:

答案 0 :(得分:1)

  1. 为您的地址创建部分内容
  2. 为购物车创建零件

将它们放入您的视图...

@model Something.Models.MyMainViewModel
<div>
    <div>
         @Html.Partial("~/Views/MyMain/AddressPartial.cshtml", Model.Address)
    </div>
    <div>
         @Html.Partial("~/Views/MyMain/ShoppingCartPartial.cshtml", Model.ShoppingCart)
    </div>
</div>

public class MyMainViewModel : ViewModelBase
{
    #region <Constructors>

    public MyMainViewModel(IApplication application, int id) : base(application)
    {
        Address = Application.GetAddress(id); //<-- From the base class
        ShoppingCart = Application.GetShoppingCart(id); //<-- From the base class
    }

    #endregion

    #region <Properties>

    public Address Address { get; set; }

    public ShoppingCart ShoppingCart { get; set; }

    #endregion
}

public class MainViewController : BaseController
{
    #region <Actions>

    [HttpGet]
    public ActionResult DoSomething(int id)
    {           
        var viewModel = new MyMainViewModel(application, id);

        return View("MyView", viewModel);
    }

    #endregion
}

public class ViewModelBase
{
    #region <Constructors>

    public ViewModelBase(IApplication application)
    {
        Application = (MyApplication)application;
    }

    #endregion

    #region <Properties>

    protected MyApplication Application { get; set; }

    #endregion
}

侧面说明:
考虑将所有Linq查询移至业务层,并使表示层仅与业务(应用程序)层“对话”。这是更干净的工具,它使应用程序更“便携”并提高了可测试性。

  • 唯一的警告是当Linq查询特定于表示层时...但是说实话...这应该很少。

答案 1 :(得分:0)

有一个包含两个子视图模型的主视图模型。这样的事情会起作用:

    public class SomePageViewModel
    {
        private IAddressService _addressService;
        private IShoppingCartService _shoppingCartService;

        public SomePageViewModel(
            IAddressService addressService,
            IShoppingCartService shoppingCartService)
        {
            _addressService = addressService;
            _shoppingCartService = shoppingCartService;
        }

        public async Task GetDataAsync()
        {
            Address = await _addressService.GetAddressViewModelAsync();
            ShoppingCart = await _shoppingCartService.GetShoppingCartAsync();
        }

        public AddressViewModel Address { get; private set; }

        public ShoppingCartViewModel ShoppingCart { get; private set; }
    }

您的LINQ语句将分别包含在IAddressServiceIShoppingCartService中(或者您可能直接调用存储库)。

希望这会有所帮助。

答案 2 :(得分:0)

创建一个包含其他两个视图模型的单一视图模型:

<div>
    @Html.Partial("[path]", Model.AddressModel)
    @Html.Partial("[path]", Model.ShoppingCartModel)
</div>

然后返回该模型。

从那里您只需要创建两个部分:

df[["new1","new2","new3"]]=pd.DataFrame(df.objs_0.values.tolist(),index=df.index)