更新时间:2023-02-01 10:32:05
第一件事,第一,不绑定在订单实体。千万不要绑定到EF对象,总是试图用的视图模型。使得视野中的生活比较简单,那就是这里的目标。
First thing's first, don't bind to the Order entity. Never bind to an EF object, always try and use a ViewModel. Makes life simpler for the View, and that is the goal here.
所以,有这样的视图模型:
So, have a ViewModel like this:
public class CreateOrderViewModel
{
public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public int SelectedProductId { get; set; }
public IEnumerable<SelectListItem> Products { get; set; }
}
这就是它现在。
返回,为您的查看你的 [HTTPGET]
控制器动作:
Return that to your View in your [HttpGet]
controller action:
[HttpGet]
public ActionResult Create()
{
var model = new CreateOrderViewModel
{
Products = db.Products
.ToList() // this will fire a query, basically SELECT * FROM Products
.Select(x => new SelectListItem
{
Text = x.ProductName,
Value = x.ProductId
});
};
return View(model);
}
然后呈现出产品的名单:(基本的HTML除外)
Then to render out the list of Products: (basic HTML excluded)
@model WebApplication.Models.CreateOrderViewModel
@Html.DropDownListFor(model => model.SelectedProductId, Model.Products)
我不知道该怎么做的唯一事情就是绑定到DateTime字段。我猜你会需要它呈现出的日期选择器什么的一个扩展方法(HTML帮助)。该视图(创建新订单),就默认为 DateTime.Now
。
现在,到 [HttpPost]
控制器动作:
[HttpPost]
public ActionResult Create(CreateOrderViewModel model)
{
try
{
// TODO: this manual stitching should be replaced with AutoMapper
var newOrder = new Order
{
OrderDate = DateTime.Now,
OrderProduct = new OrderProduct
{
ProductId = SelectedProductId
}
};
db.Orders.AddObject(newOrder);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
现在,我也觉得你的EF模型需要的工作。
Now, i also think your EF model needs work.
要我(英文术语),一个产品可以有多个订单,一个订单可以有很多产品。
因此,它应该是一个多对许多。目前,它是一个1-1冗余连接表。你有没有产生来自DB?如果是这样,你可能DB需要的工作。
So, it should be a many-to-many. Currently it's a 1-1 with a redundant join table. Did you generate that from a DB? If so, your DB possibly needs work.
您应该有一个导航属性时调用的产品的订单实体,它引用的产品的集合,通过无声成为可能加盟在连接表许多一对多。
You should have a navigational property called Products on the Order entity, which references a collection of Product, made possible by a silent join to the join table in the many-to-many.
这也意味着你不再有一个DropDownList,而是一个MultiSelectDropDownList。
This also means you no longer have a DropDownList, but a MultiSelectDropDownList.