我对来自 aspx 世界的 MVC 的理解有困难。
我有一个名为CustomerGarment
. 这有一个Order
和一个Customer
以及一些服装。
public class CustomerGarment
{
public int CustomerGarmentId { get; set; }
public virtual Customer Customer { get; set; }
public virtual Order Order { get; set; }
public virtual GarmentJacket GarmentJacket { get; set; }
public virtual GarmentShirt GarmentShirt { get; set; }
}
我有一种获取和发布的方法。当页面加载时,它会创建一个新CustomerGarment
实例并查询数据库以填充 Customer 和 Order 变量。然后我使用 viewbag 在屏幕上显示GarmentJacket
s 和GarmentShirt
s的列表
然后页面查看并使用该视图我可以完美地访问模型。下拉菜单加载视图包内容,我可以使用我传递的模型访问所有 Customer 和 Order 变量。
然后我面临的问题是当我使用 HttpPost 时。模型不会与我传递给它的信息一起传回。
public ActionResult AddGarments(int orderId, int customerId)
{
CustomerGarment cg = new CustomerGarment();
cg.Order = (from a in db.Orders where a.OrderId == orderId select a).FirstOrDefault();
cg.Customer = (from a in db.Customers where a.CustomerId == customerId select a).FirstOrDefault();
var jackets = from a in db.GarmentJackets orderby a.Type, a.SleeveLengthInches, a.ChestSizeInches select a;
var shirts= from a in db.GarmentKilts orderby a.PrimarySize, a.DropLength select a;
ViewBag.GarmentJacket = new SelectList(jackets, "GarmentJacketId", "GarmentJacketId");
ViewBag.GarmentShirt = new SelectList(shirts, "GarmentShirtId", "GarmentShirtId");
return View(cg);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddGarments(CustomerGarment cg)
{
// Here, I do not have the customer info for example
db.CustomerGarments.Add(cg);
db.SaveChanges();
return RedirectToAction("Index");
return View(cg);
}
这是我的一点看法
@Html.HiddenFor(model => model.Order.OrderId)
@Html.HiddenFor(model => model.Order.CustomerId)
<div class="display-field">
@Html.DisplayFor(model => model.Customer.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.GarmentJacket, "Jacket")
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.GarmentJacket, (SelectList)ViewBag.GarmentJacket, new {style="width:312px;height:30px;margin-top:2px;margin-bottom:5px"})
</div>
编辑
我的服装夹克模型
public class GarmentJacket : Garment
{
public int GarmentJacketId { get; set; }
[Required]
public string Type { get; set; }
[Required]
[Display(Name = "Chest Size")]
public int ChestSizeInches { get; set; }
[Required]
[Display(Name = "Sleeve Length")]
public int SleeveLengthInches { get; set; }
}
public class Garment
{
[DataType(DataType.Date)]
public DateTime? DateRetired { get; set; }
[Required]
public string Barcode { get; set; }
[Required]
public bool Adults { get; set; }
}