-1

I have a Property Last_edited in my Model an want to set this on code side. I also have properties like Name which should set by User. I use Code First and this Edit method was generated by Entity Framework. I haven't found anything how to do it.

Here's my Controller Edit method:

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);
}
Blacky.17
  • 25
  • 5

1 Answers1

2

Remove Last_edited from the Include list of Bind attribute and set the value yourself in the action method.

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

Assuming Last_edited is of DateTime type. if it is a different type, set the appropriate value.

Since we are setting the value of this property in the action method, there is no need to keep an input field for this property in the form.

As a side note, The best way to prevent overposting is by using a (view specific) view model class. This also allows you to create loosely coupled programs.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • is'nt better would be to use viewmodel with only propeties that are needed to be passed via view? – Ehsan Sajjad Jan 17 '17 at 15:19
  • Yes. The best & loosely coupled way to [prevent overposting is by using a view model](http://stackoverflow.com/questions/34260334/mvc-6-bind-attribute-disappears/34260397#34260397). The OP is new to MVC and is playing with the code generated by the IDE. I did not want to confuse him. I will update the answer to include the link – Shyju Jan 17 '17 at 15:25
  • yeah, that would be good to add, that better approach is this for future readers.. – Ehsan Sajjad Jan 17 '17 at 15:35