Reputation: 2005
I have a CompanyCode
that is readonly and has to be displayed to the user. I have no say in preventing this from being the primary key. How can I prevent the user from updating this field at all on the server-side?
I've tried the following:
company.Property(s => s.CompanyCode).IsModified = false;
However, this throws an error that the key field can't be modified. Is there an easy way to prevent the user from changing the key field or telling Entity Framework not to attempt to update this field?
Upvotes: 0
Views: 617
Reputation: 239360
You should always, always, always, update the entity pulled fresh from the database with the posted values, rather than saving the posted version directly to the database. Therefore, all you need to do is pass the id in the URL:
public ActionResult Edit(int id, CompanyViewModel model)
{
var company = db.Companies.Find(id);
if (company == null)
{
return new HttpNotFoundResult();
}
if (ModelState.IsValid)
{
// map `model` properties to `company` properties
db.Entry(company).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
Upvotes: 2
Reputation: 10139
If I'm understanding you correctly, and you must show this CompanyCode
on the UI, just display the company code using @Html.DisplayFor(model => model.CompanyCode)
on your View, instead of EditorFor
which renders a text box in which case, if you render a textbox, this value would be able to be updated. Does this make sense
EDIT
If you need this to post back to the server, make it @Html.EditorFor(model => model.CompanyCode)
and simply disable this control via JavaScript.
Upvotes: 0