Change value only in MVC edit pattern

I have setup a class that does not exceed ID

, Name

, Value

.

I created a basic controller template and it works well.

default code:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ID,Name,Value")] ConfigOption config)
{
    if (ModelState.IsValid)
    {
        db.Entry(config).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(config);
}

      

I want the user to be able to change the settings values, but not the name after clicking the Edit button, so I removed the edit box from the page, however this now causes the name to go blank on save.

I know I can do what I want by editing the part if (ModelState.IsValid)

, manually finding the ID and then doing my own mapping and saving, but I haven't touched MVC since version 3 and I could swear it was easier / then the edit pattern was more accurate.

... Is there an easy way to just change one field? - I even tried to grab Name

from the bindings section, but I can't say that I fully understand it ... I need to catch up with new features.

+3


source to share


1 answer


Since HTTP is statusless, you need to provide a name value for the Edit method as well. Just think about how EF can decide from an empty name value (which is what you have here now) if it means you want the property not to change or you want its value to be empty.

You either put the name field in the view as hidden, but you still have to worry about the user being able to change the value of the hidden field, or you have to do something like this:



[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ID,Name,Value")]     ConfigOption model)
{
  if (ModelState.IsValid)
  {
     var config=db.Configs.Find(model.ID);
     config.Value=model.Value;
     await db.SaveChangesAsync();
     return RedirectToAction("Index");
  }
  return View(config);
}

      

The Bind attribute next to the action parameter should prevent an attack called bulk assignment / overflow. More details here: http://ironshay.com/post/Mass-Assignment-Vulnerability-in-ASPNET-MVC.aspx

+1


source







All Articles