C# 模型绑定在 'db.SaveChanges' 之前修改 属性

C# Model Binding modify property before 'db.SaveChanges'

我正在尝试对简单的 CRUD 进行以下更改,但没有成功。

APP包含2个模型,2个控制器和每个控制器的CRUD视图。

'Stores' 和 'Products' 控制器。我需要创建一个新商店,然后创建与创建的新商店相关的产品

'Create' 视图具有以下内容:

<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 个属性,Location、Description 和 Note。控制器代码:

 [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(); 

但我不希望用户在视图上创建它。我想在数据库上自动分配这个值。我正朝着正确的方向前进吗?谢谢

不要将其作为模型从视图中传递。只需在控制器中设置即可。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Location,Description,Notes")] Store store)
    {

        if (ModelState.IsValid)
        {
            store.CreateDate = DateTime.Now;
            db.Stores.Add(store);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(store);
    }