ASP.NET MVC 3 Update, ObjectStateManager, Concurrency - asp.net-mvc-3

I am trying to modify model coming from View and then update my database using that model. My code can be seen below:
public ActionResult Edit(Saving saving)
{
if (ModelState.IsValid)
{
Int32[] ids = saving.CatIds.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
foreach (var category in db.Category.Where(m => ids.Contains(m.id)).ToList())
saving.Category.Add(category);
db.ObjectStateManager.ChangeObjectState(saving, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(saving);
}
my code gives this error:
The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state.
and if I try this code:
public ActionResult Edit(Saving saving)
{
if (ModelState.IsValid)
{
Int32[] ids = saving.CatIds.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
foreach (var category in db.Category.Where(m => ids.Contains(m.id)).ToList())
saving.Category.Add(category);
db.ObjectStateManager.ChangeObjectState(saving, EntityState.Unchanged);
db.Saving.Attach(saving);
db.ObjectStateManager.ChangeObjectState(saving, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(saving);
}
I am getting the error below:
Violation of PRIMARY KEY constraint 'PK_ProductCategory_1'. Cannot insert duplicate key in object 'dbo.ProductCategory'.
I dont know what to do and how to solve it. Any help will be appreciated. Thank You

Have you tried to just Attach it and then modify the properties?
if (ModelState.IsValid)
{
db.Saving.Attach(saving);
Int32[] ids = saving.CatIds.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
foreach (var category in db.Category.Where(m => ids.Contains(m.id)).ToList())
saving.Category.Add(category);
db.SaveChanges();
}

Related

.Net MVC verify only one checkox checked

I have a model called Employee with a boolean field called OnDuty. Our business rules only allow for one employee on duty.
On the index page, I've setup the checkbox so they trigger an update call to update the employee as being "on call". However, I'm not set any other employees to off duty using my controller action below. How do I go about making sure that no other employee is on duty?
[HttpPost]
public JsonResult Update(Employee employee)
{
IEnumerable<Employee> onCallEmployee = _db.Employees.Where(e => e.OnCall == true);
foreach (Employee e in onCallEmployee) {
e.OnCall = false;
_db.Entry(e).State = EntityState.Modified;
_db.SaveChanges();
}
_db.Entry(employee).State = EntityState.Modified;
_db.SaveChanges();
return Json("Employee updated!");
}
It appears that my error(s) were caused by the way I was trying to update the employees. I had to exclude the employee which was already being updated by the function from onCallEmployee because it would throw an error (Attaching an entity of type 'Employee' failed because another entity of the same type already has the same primary key value.) when trying to save the updates.
Also, based on #mwwallace8, suggestion, I removed the SaveChanges() call from the for loop and left a single call at the end.
[HttpPost]
public JsonResult Update(Employee employee)
{
IEnumerable<Employee> onCallEmployee = _db.Employees.Where(e => e.OnCall == true && e.ID != employee.ID);
foreach (Employee e in onCallEmployee) {
e.OnCall = false;
_db.Entry(e).State = EntityState.Modified;
}
_db.Entry(employee).State = EntityState.Modified;
_db.SaveChanges();
return Json("Employee updated!");
}

update single value in EF 4.0

i m working on MVC application and using Entity Framework 4.0 for database connection.While editing record i want to update some fields in table. code for edit is
[HttpPost]
public ActionResult Edit(ProjectActivityDetail projectactivitydetail, FormCollection formcollection)
{
if (ModelState.IsValid)
{
string value = Request["ChkIntBool"];
if (value.Substring(0, 4) == "true") { projectactivitydetail.IsApproved = 1; } else { projectactivitydetail.IsApproved = 0; }
projectactivitydetail.ProjectActivityDID = long.Parse(Session["ProjectActivityDID"].ToString());
projectactivitydetail.UpatedBy = long.Parse(Session["UserID"].ToString());
projectactivitydetail.UpdatedON = System.DateTime.Now;
db.Entry(projectactivitydetail).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FK_ProjectActivityID = new SelectList(db.ProjectActivityMasters, "ProjectActivityID", "ActivityName", projectactivitydetail.FK_ProjectActivityID);
return View(projectactivitydetail);
}
i just want to update these fields but when this executred my other fields updated to null , is there any way i can keep those values as it is and update these many values in database table.please help
It looks like the entity being passed into the service call is not complete. My advice would be to find the existing entity and make the changes to that rather than attaching the one passed in:
[HttpPost]
public ActionResult Edit(ProjectActivityDetail projectactivitydetail, FormCollection formcollection)
{
if (ModelState.IsValid)
{
//I'm assuming the PK of the entity is id so adjust for that
var entity = db.Set<ProjectActivityDetail>().Find(projectactivitydetail.id);
string value = Request["ChkIntBool"];
entity.IsApproved = value.Substring(0, 4) == "true" ? 1 : 0;
entity.ProjectActivityDID = long.Parse(Session["ProjectActivityDID"].ToString());
entity.UpatedBy = long.Parse(Session["UserID"].ToString());
entity.UpdatedON = System.DateTime.Now;
db.Entry(entity).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FK_ProjectActivityID = new SelectList(db.ProjectActivityMasters, "ProjectActivityID", "ActivityName", projectactivitydetail.FK_ProjectActivityID);
return View(projectactivitydetail);
}
Yes, there's a way. Add hidden fields to your view with the data you want to persist on the model, int this case ProjectActivityDetail, this way the properties will get bound to the projectactivitydetail variable on the model binding stage.
Suppose you have a property called CreatedOn that is being set to null, on your view you'd add:
#Html.HiddenFor(model => model.CreatedOn)
Then, when you submit the form the value originally on CreatedOn will be bound to the property at projectactivitydetail and your model will be saved just fine. Your fields are being updated to null because model binding is not finding any values for them.
Good luck.

Is this the correct way to save form values in MVC3?

Here's my code:
[HttpGet]
public ActionResult Register()
{
RegisterViewModel model = new RegisterViewModel();
using (CityRepository city = new CityRepository())
{
model.SelectCityList = new SelectList(city.FindAllCities().ToList(), "CityID", "CityName");
}
using (CountryRepository country = new CountryRepository())
{
model.SelectCountryList = new SelectList(country.FindAllCountries().ToList(), "CountryID", "CountryName");
}
return View(model);
}
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
//Actually register the user here.
RedirectToAction("Index", "Home");
}
//Something went wrong, redisplay the form for correction.
return View(model);
}
Is this the best approach or is there another better tested way? Keep in mind that my database tables/field names are nothing like what I declared in my models. I have to scrape the values from the ViewModel and put them into an entity framework generated class to persist the information.
Anything here that screams out at you as wrong?
I use that pattern and another pattern which looks like this (important part is the AutoMapper part):
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
// repopulate any input or other items set in GET
// prefer to do at top due to ^^^ is easy to overlook
return View(model);
}
// if it's an edit, pull to new instance
// from the database and use automapper to
// map over the submitted values from model to instance
// then update instance in database
//
// VALUE: useful if form only shows
// some of the properties/fields of model
// (otherwise, those not shown would be null/default)
// if it's new, insert
RedirectToAction("Index", "Home");
}
That's the pattern I generally use.
I prefer this pattern:
Controller:
[HttpGet]
public ActionResult Index()
{
var cities= (from m in db.cities select m);
ViewBag.Cities= cities;
var states = (from m in db.States select m);
ViewBag.States = states;
return View();
}
[HttpPost]
public ActionResult Index(RegisterViewModel model)
{
if (ModelState.IsValid)
{
// Saving the data
return View("ActionName", model);
}
return View();
}
View:
#Html.DropDownList("DDLCities",new SelectList(ViewBag.Cities, "CityId" , "CityName" ), new { #class = "className" })
#Html.DropDownList("DDLStates",new SelectList(ViewBag.States, "StateId" , "StateName" ), new { #class = "className" })
Advised changes to [HttpGet]:
[HttpGet]
public ActionResult Register()
{
// Get
var cities = new List<City>();
var countries = new List<Country>();
using (CityRepository city = new CityRepository())
{
cities = city.FindAllCities().ToList();
}
using (CountryRepository country = new CountryRepository())
{
counties = country.FindAllCountries().ToList();
}
// Map.
var aggregatedObjects = new SomePOCO(cities, countries);
var model = Mapper.Map<SomePOCO,RegisterViewModel>(aggregatedObjects );
// Return
return View(model);
}
Summary of changes:
Layout your logic in such a way the controller's job makes sense. Get - Map - Return. Exactly the tasks (in order) for which a Controller is designed for.
Use AutoMapper to do the heavy lifting of ViewModel creation for you.
Advised changes to your [HttpPost]:
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
return View(model);
try
{
var dbObj = Mapper.Map<RegisterViewModel,SomeDomainObj>(model);
_repository.Save(dbObj);
return RedirectToAction("Index");
}
catch (Exception exc)
{
if (exc is BusinessError)
ModelState.AddModelError("SomeKey", ((BusinessError)exc).FriendlyError);
else
ModelState.AddModelError("SomeKey", Resources.Global.GenericErrorMessage);
}
return View(model);
}
Summary of changes:
Try/catch. Always need to capture exceptions, whether they are domain exceptions or lower-level (database ones)
Check ModelState validity first. As #Cymen says - do it first so you don't forget later
Add exceptions to ModelState. Use custom exception classes for business errors with descriptive, resource-based messages. If the error is too low-level for the user (foreign key constraint, etc), show a generic message

RedirectToAction after validation errors

If I have the usual Edit actions, one for GET to retrieve an object by it's ID and to display it in an edit form. The next for POST to take the values in the ViewModel and update the object in the database.
public virtual ActionResult Edit(int id)
[HttpPost]
public ActionResult Edit(VehicleVariantEditSaveViewModel viewModel)
If an error occurs during model binding in the POST action, I understand I can RedirectToAction back to the GET action and preserve the ModelState validation errors by copying it to TempData and retrieving it after the redirect in the GET action.
if (TempData["ViewData"] != null)
{
ViewData = (ViewDataDictionary)TempData["ViewData"];
}
How do I then convert that ViewData, which includes the previous invalid ModelState, into a new model to send to the view so the user sees their invalid input with validation warnings? Oddly enough if I pass in a new instance of my ViewModel retrieved from the database (with the original valid data) to the View() this is ignored and the (invalid) data in the ViewData is displayed!
Thanks
I had a similar problem and decided to use the following pattern:
public ActionResult PersonalRecord(Guid id)
{
if (TempData["Model"] == null)
{
var personalRecord = _context.PersonalRecords.Single(p => p.UserId == id);
var model = personalRecord.ToPersonalRecordModel();
return View(model);
}
else
{
ViewData = (ViewDataDictionary) TempData["ViewData"];
return View(TempData["Model"]);
}
}
[HttpPost]
public ActionResult PersonalRecord(PersonalRecordModel model)
{
try
{
if (ModelState.IsValid)
{
var personalRecord = _context.PersonalRecords.Single(u => u.UserId == model.UserId);
personalRecord.Email = model.Email;
personalRecord.DOB = model.DOB;
personalRecord.PrimaryPhone = model.PrimaryPhone;
_context.Update(personalRecord);
_context.SaveChanges();
return RedirectToAction("PersonalRecord");
}
}
catch (DbEntityValidationException ex)
{
var errors = ex.EntityValidationErrors.First();
foreach (var propertyError in errors.ValidationErrors)
{
ModelState.AddModelError(propertyError.PropertyName, propertyError.ErrorMessage);
}
}
TempData["Model"] = model;
TempData["ViewData"] = ViewData;
return RedirectToAction("PersonalRecord", new { id = model.UserId });
}
Hope this helps.
I noticed that the Model is included in ViewData so you don't need to pass it in addition to the ViewData, what I don't understand is how you get at it to then return it to the view.
public ViewResult Edit(int id)
{
// Check if we have ViewData in the session from a previous attempt which failed validation
if (TempData["ViewData"] != null)
{
ViewData = (ViewDataDictionary)TempData["ViewData"];
}
VehicleVariantEditViewModel viewModel = new VehicleVariantControllerViewModelBuilder()
.BuildForEdit(id);
return View(viewModel);
}
The above works but obviously it's making an unnecessary call to the database to build a new Model (which gets automagically overwritten with the invalid values from the Model in the passed ViewData)
Confusing.

MVC Delete record but how to code this in Controller

I'm a beginner of MVC3 with ASP.Net (C#) but I don't get the next situation to delete a record.
I have a View that ask the user to confirm delete a item (record). As code I have this to initialize the view:
public ActionResult KeywordsDelete(Guid id)
{
_db = new BlaContext();
return _db.SearchTerms.Where(x => x.id.Equals(id)).First();
}
But when confirmed, then I have the next code.
[HttpPost]
public ActionResult KeywordsDelete(Guid id)
{
_db = new BlaContext();
var term = _db.SearchTerms.Where(x => x.id == id).First();
_db.SearchTerms.Remove(term);
_db.SaveChanges();
return View("Keywords", _db.SearchTerms.ToList());
}
Building is not possible because the signature of this method is already exists (same parameters and method name).
So I don't get how to delete a record in this situation. The view is created with a default Scaffold template (delete).
I found an alternative solution to this problem while reading up on MVC. Check out: Improving the Details and Delete Methods
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id = 0)
{
// Delete stuff...
}
This will route the action Delete to the method DeleteConfirmed.
You can give your post function another additional parameter
[HttpPost]
public ActionResult KeywordsDelete(Guid id, FormCollection collection)
{
_db = new BlaContext();
var term = _db.SearchTerms.Where(x => x.id == id).First();
_db.SearchTerms.Remove(term);
_db.SaveChanges();
return View("Keywords", _db.SearchTerms.ToList());
}
But your GET Action should also return a View not a data object, I think.
public ActionResult KeywordsDelete(Guid id)
{
_db = new BlaContext();
return View(_db.SearchTerms.Where(x => x.id.Equals(id)).First());
}

Resources