【问题标题】:MVC set specific properties code sideMVC 设置特定属性代码端
【发布时间】:2017-01-17 15:03:32
【问题描述】:

我的模型中有一个属性Last_edited,我想在代码端设置它。我也有像Name 这样的属性,应该由用户设置。我使用 Code First,这个 Edit 方法是由实体框架生成的。我还没有找到任何方法。

这是我的控制器编辑方法:

public ActionResult Edit(int? id)
{
    if (id == null)
    {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Product product = db.Product.Find(id);
        if (product == null)
        {
            return HttpNotFound();
        }
        return View(product);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Comment,Last_edited")] Product product)
{
    if (ModelState.IsValid)
    {
        db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
    }
        return View(product);
}

【问题讨论】:

  • 或者就这样保留它并将 Last_edited 也设置为服务器端。作为覆盖
  • 如果您只需要代码端的 Last_edited,并且不想在视图中显示它,只需从“include”语句中删除 ir。

标签: c# asp.net-mvc entity-framework controller


【解决方案1】:

Bind 属性的 Include 列表中删除 Last_edited 并在操作方法中自行设置值。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Comment")] Product product)
{
    product.Last_Edited = DateTime.UtcNow;
    if (ModelState.IsValid)
    {           
        db.Entry(product).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(product);
}

假设Last_editedDateTime 类型。如果是不同的类型,设置适当的值。

由于我们是在 action 方法中设置这个属性的值,所以不需要在表单中为这个属性保留一个输入字段。

作为旁注,The best way to prevent overposting is by using a (view specific) view model class。这也允许您创建松散耦合的程序。

【讨论】:

  • 最好是使用仅需要通过视图传递的属性的视图模型?
  • 是的。 prevent overposting is by using a view model 的最佳和松耦合方式。 OP 是 MVC 的新手,正在使用 IDE 生成的代码。我不想混淆他。我将更新答案以包含链接
  • 是的,这将是很好的补充,更好的方法是未来的读者..
猜你喜欢
  • 2019-10-24
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-03
  • 2011-02-02
相关资源
最近更新 更多