【发布时间】:2020-02-25 23:02:32
【问题描述】:
我的控制器中有以下控制器创建操作。请注意选择列表中的显示名称将是“StoreName - StoreAddress”。 Store complexType 存储在 Store 中。
// GET: Purchases/Create
public ActionResult Create()
{
ViewBag.Stores = db.Stores.Select(s => new { DisplayName = s.StoreName.ToString() + " - " + s.Address.ToString(), Store = s});
return View();
}
在创建视图中,以下代码会确保正确显示。
<div class="form-group">
@Html.LabelFor(model => model.Store.StoreName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Store.StoreName, new SelectList(ViewBag.Stores, "Store", "DisplayName"), new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Store.StoreName, "", new { @class = "text-danger" })
</div>
</div>
它将转到控制器的 post 方法(如果我是正确的)。
// POST: Purchases/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Store,Price,Date")] Purchase purchase)
{
if (ModelState.IsValid)
{
Store store = purchase.Store;
db.Purchases.Add(purchase);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(purchase);
}
不过,Store store = purchase.Store 现在将给出一个复杂的 Store 类型,其中除 StoreName 之外的任何值都设置为 null。 StoreName 将是一个字符串。
如何获得与所选 Store 对象相等的复杂类型返回?
编辑1:
public class Purchase
{
public int Id { get; set; }
public Store Store { get; set; }
public string Type { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
public decimal Price { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
}
public class PurchaseDBContext : DbContext
{
public DbSet<Purchase> Purchases { get; set; }
public DbSet<Store> Stores { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
public class Store
{
public int StoreId { get; set; }
public string StoreName { get; set; }
public string Address { get; set; }
public string City { get; set; }
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)[1-9]((\s|\s?\-\s?)?[0-9])((\s|\s?-\s?)?[0-9])((\s|\s?-\s?)?[0-9])\s?[0-9]\s?[0-9]\s?[0-9]\s?[0-9]\s?[0-9]$", ErrorMessage = "This is not a valid phonenumber")]
public string PhoneNumber { get; set; }
}
是否需要使用额外的注解来设置导航属性?
【问题讨论】:
-
我假设您使用的是像 EF 这样的 ORM。您是否为购买和商店实体设置了导航属性?
-
我已经在帖子中设置了采购和商店类。我是否需要设置额外的导航属性(如 [Key] 和 [ForeignKey("Store")])?
标签: c# html model-view-controller