Two model have combined to exist in view
1.~/Products.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShoppingStore.Domain.Entities
{
public class Product
{
public int ProductID { get; set;}
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
}
2.~/PorductListViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ShoppingStore.Domain.Entities;
namespace ShoppingStore.WebUI.Models
{
public class ProductsListViewModel
{
public IEnumerable<Product> Products { get; set; }
public PagingInfo PageInfo { get; set; }
public string CurrentCategory { get; set; }
}
}
3.control ~/ProductController.cs public ViewResult List(string category , int page=1)
{
ProductsListViewModel model = new ProductsListViewModel
{
Products = repository.Products.Where(p => category ==null || p.Category ==category).OrderBy(p => p.ProductID).Skip((page - 1) * PageSize).Take(PageSize),
PageInfo = new PagingInfo {CurentPage = page,ItemPerPage = PageSize,TotalItems = category == null ? repository.Products.Count() : repository.Products.Where(e => e.Category == category).Count()},
CurrentCategory = category
};
return View(model);
}
i use this way Multiple models in a view
and add two model in one model
1.~/MainPageModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ShoppingStore.Domain.Entities;
namespace ShoppingStore.WebUI.Models
{
public class MainPageModel
{
public ProductsListViewModel ProductsListViewModel { get; set; }
public Product Product { get; set; }
}
}
and chnage code like below
~/List.cshtml
@model ShoppingStore.WebUI.Models.MainPageModel
@{
ViewBag.Title = "Prodcuts";
}
@foreach (var p in Model.PorductListViewModel.Products)
{
@Html.Partial("ProductSummary",p)
}
<div>
@Html.PageLinks(Model.PorductListViewModel.PageInfo, x => Url.Action("List", new { page = x , category = Model.PorductListViewModel.CurrentCategory }))
</div>
<div>
@using (Html.BeginForm())
{
<div >
@Html.HiddenFor(x => x.Product.ProductID)
@Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" value="Add to cart" />
</div>
<div>
<div id='DIV2'><input type="button" onclick="incrementValue1()" value="ADD" /></div>
<div id="DIV2"> <input type="text" id="number1" value="0" /></div>
<div id="DIV2"><input type="button" onclick="decrementValue1()" value="minus" /></div>
</div>
<button id="checkvalue" onclick="checkValue()" type="submit">Check</button>
</div>
}
When Running , IIS have below error message .
The model item passed into the dictionary is of type 'ShoppingStore.WebUI.Models.ProductsListViewModel', but this dictionary requires a model item of type 'ShoppingStore.WebUI.Models.MainPageModel'.
why have this error message