“db.SaveChanges”之前的C#模型绑定修改属性

时间:2016-11-24 22:26:05

标签: c# asp.net-mvc crud controllers

我在一个简单的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(); 

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

1 个答案:

答案 0 :(得分:0)

不要从视图中将其作为模型传递。只需在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);
    }