C# MVC集合特定属性代码端

C# MVC集合特定属性代码端,c#,asp.net-mvc,entity-framework,controller,C#,Asp.net Mvc,Entity Framework,Controller,我的模型中有一个上次编辑的属性,,我想在代码端设置它。我还有像Name这样的属性,应该由用户设置。我首先使用代码,这个编辑方法是由实体框架生成的。我还没有找到任何方法 以下是我的控制器编辑方法: public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); }

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

以下是我的控制器编辑方法:

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

Bind
属性的Include列表中删除上次编辑的

[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);
}
假设上次编辑的
DateTime
类型。如果是其他类型,请设置适当的值

由于我们在action方法中设置此属性的值,因此不需要在表单中保留此属性的输入字段


作为旁注。这还允许您创建松散耦合的程序。

或者只需保持这样,并在服务器端设置Last_edited。作为OVERRIDEI,如果您只需要在代码端编辑最后一次,并且您不想在视图中显示它,只需从“include”语句中删除ir。使用viewmodel时,最好只使用需要通过视图传递的属性?是的。最好的松散耦合方式。OP对MVC来说是新的,并且正在使用IDE生成的代码。我不想把他搞糊涂。我将更新答案,以包括链接是的,这将是很好的补充,更好的方法是这对未来的读者。。