【问题标题】:C# Model Binding modify property before 'db.SaveChanges'C# 模型绑定在“db.SaveChanges”之前修改属性
【发布时间】: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


【解决方案1】:

不要将它作为模型从视图中传递。只需在 Controller 中设置即可。

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

【讨论】:

    猜你喜欢
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2012-06-24
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多