Tôi có mô hình chế độ xem có chứa loại Loại sản phẩm và loại Sản phẩm> Loại sản phẩm IEnumerable <. Trên bài đăng, đối tượng sản phẩm cấp đầu tiên được trả về ràng buộc từ viewmodel trong khi enum sản phẩm đang trở về null.Xem mô hình IEnumerable <> tài sản là trở lại null (không ràng buộc) từ phương pháp bài?
Tại sao thuộc tính IEnumerable < Prouduct> không bị ràng buộc vào mô hình xem của tôi trên mỗi bài đăng? Cám ơn!
Models:
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductIndexViewModel
{
public Product NewProduct { get; set; }
public IEnumerable<Product> Products { get; set; }
}
public class BoringStoreContext
{
public BoringStoreContext()
{
Products = new List<Product>();
Products.Add(new Product() { ID = 1, Name = "Sure", Price = (decimal)(1.10) });
Products.Add(new Product() { ID = 2, Name = "Sure2", Price = (decimal)(2.10) });
}
public List<Product> Products {get; set;}
}
Xem:
@model ProductIndexViewModel
@using (@Html.BeginForm())
{
<div>
@Html.LabelFor(model => model.NewProduct.Name)
@Html.EditorFor(model => model.NewProduct.Name)
</div>
<div>
@Html.LabelFor(model => model.NewProduct.Price)
@Html.EditorFor(model => model.NewProduct.Price)
</div>
<div>
<input type="submit" value="Add Product" />
</div>
foreach (var item in Model.Products)
{
<div>
@Html.LabelFor(model => item.ID)
@Html.EditorFor(model => item.ID)
</div>
<div>
@Html.LabelFor(model => item.Name)
@Html.EditorFor(model => item.Name)
</div>
<div>
@Html.LabelFor(model => item.Price)
@Html.EditorFor(model => item.Price)
</div>
}
}
Bộ điều khiển:
public class HomeController : Controller
{
BoringStoreContext db = new BoringStoreContext();
public ActionResult Index()
{
ProductIndexViewModel viewModel = new ProductIndexViewModel
{
NewProduct = new Product(),
Products = db.Products
};
return View(viewModel);
}
[HttpPost]
public ActionResult Index(ProductIndexViewModel viewModel)
{
// ???? viewModel.Products is NULL here
// ???? viewModel.NewProduct comes back fine
return View();
}
Bạn có tùy chỉnh EditorFor của bạn? – Shyju
@Shyju: Xin chào, tôi không .. Tôi giả định rằng nếu tôi tạo một EditorTemplate cho Product.cshtml tôi có thể gọi @ HTml.EditorFor (model => model.Products) và nó có thể sẽ hoạt động? – JaJ
Có thể. Tôi đã thêm một câu trả lời với cách tiếp cận đó. – Shyju