【发布时间】:2016-11-24 22:26:04
【问题描述】:
我正在尝试对简单的 CRUD 进行以下更改,但没有成功。
APP 包含 2 个模型、2 个控制器和每个控制器的 CRUD 视图。
“商店”和“产品”控制器。我需要创建一个新商店,然后创建与创建的新商店相关的产品
“创建”视图具有以下内容:
<div class="form-horizontal">
<h4>Store</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Location, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Location, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Location, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Notes, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Notes, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" })
</div>
</div>
如您所见,有 3 个属性,位置、描述和注释。控制器代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Location,Description,Notes,StoreCode")] Store store)
{
if (ModelState.IsValid)
{
db.Stores.Add(store);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(store);
}
我正在尝试在此绑定模型中添加一个名为“StoreCode”的第四个属性,以将其插入到我的数据库中
StoreCode.DateTime.Now.ToFileTime();
但我不希望用户在视图上创建它。我想在数据库上自动分配这个值。我在朝着正确的方向前进吗?谢谢
【问题讨论】:
-
不需要像这样
Bind(Include = "Location,Description,Notes")包含StoreCode然后在db.Stores.Add(store)之前设置它像这样store.StoreCode = "yourcode"
标签: c# asp.net-mvc crud controllers