Reputation: 2127
I have a settings class that is no more than ID
, Name
, Value
.
I've done a basic controller scaffolding template and it works well.
the default code is:
[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 setting values, but, not the name after clicking edit, so, I deleted the edit box from the page - however, this now causes the name to become blank upon saving.
I know I can do what I want by editing the if (ModelState.IsValid)
part, manually finding the id and then performing my own mapping and saving, but, I haven't touched MVC since version 3 and I could swear it was easier/the edit template was neater back then.
...Is there a simpler way of just modifying one field? - I've even tried taking Name
off the bind section, but, I can't say I fully understand that... I need to catch up on the new features.
Upvotes: 3
Views: 460
Reputation: 635
Since HTTP is stateless, you need to provide the name value also to the Edit method. Just think it through, how can EF decide from an empty name value (what you have here right now) if it represent that you want the property unchanged or you want it to be set to empty.
You either place back the name field to the view as hidden, but you still should worry about that the user can change the value of the hidden field, or you should 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's parameter is supposed to prevent the attack called mass assignment/overposting. Find out more here: http://ironshay.com/post/Mass-Assignment-Vulnerability-in-ASPNET-MVC.aspx
Upvotes: 1