.Net MVC verify only one checkox checked - validation

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!");
}

Related

how to delete data from in mvc3

I want to delete the data. here is my code. when i trying to delete the data it gives an error.
this is my code
public ActionResult delete(Int32 id)
{
var contentdelete = (from m in _db.tb_content
where m.id == id
select m).First();
return View(contentdelete);
}
public ActionResult delete(MvcNTL.Models.tb_content contentdelete)
{
var content = (from m in _db.tb_content
where m.id == contentdelete.id
select m).First();
if (!ModelState.IsValid)
return View(content);
_db.ApplyCurrentValues(content.EntityKey.EntitySetName, contentdelete);
_db.SaveChanges();
return RedirectToAction("index");
}
this is the error
The current request for action 'delete' on controller type 'ContentController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult delete(Int32) on type MvcNTL.Controllers.ContentController
System.Web.Mvc.ActionResult delete(MvcNTL.Models.tb_content) on type MvcNTL.Controllers.ContentController
You need to add [HTTPPOST] At your second delete controller. They both are get controllers now, so mvc doesn't know which one to pick.
You cannot have 2 actions with the same name on the same controller accessible with the same HTTP verb. You should decorate the second one with the [HttpPost] attribute:
[HttpPost]
public ActionResult delete(MvcNTL.Models.tb_content contentdelete)
{
var content = (from m in _db.tb_content
where m.id == contentdelete.id
select m).First();
if (!ModelState.IsValid)
return View(content);
_db.ApplyCurrentValues(content.EntityKey.EntitySetName, contentdelete);
_db.SaveChanges();
return RedirectToAction("index");
}
This makes the second action that is actually performing the delete accessible only with the POST verb. The first action will be accessible with the GET verb and would render the form.
[HttpPost]
public ActionResult delete(MvcNTL.Models.tb_content contentdelete)
{
var content = (from m in _db.tb_content
where m.id == contentdelete.id
select m).First();
if (!ModelState.IsValid)
return View(content);
_db.ApplyCurrentValues(content.EntityKey.EntitySetName, contentdelete);
_db.SaveChanges();
return RedirectToAction("index");
}

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.

ASP.NET MVC 3 Update, ObjectStateManager, Concurrency

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

Values on PostBack getting lost

I am using MVC3 and classes generetad from EntityFranmework for saving some data into a Database.
The controller
// Get
public ActionResult Create(Guid StudentID)
{
Semester semester = new Semester();
ViewBag.BranchID = new SelectList(db.Branches, "ID", "Name");
semester.Student = db.Students.Single(s => s.ID == StudentID);
return PartialView(semester);
}
//
// POST: /Semester/Create
[HttpPost]
public ActionResult Create(Semester semester)
{
semester.ID = Guid.NewGuid();
semester.CreatedDate = DateTime.Now;
semester.CreatedBy = "ddf";
db.Semesters.AddObject(semester);
db.SaveChanges();
return RedirectToAction("Index", "Student");
}
I do get all the result of the student at get Method but all the student data are Lost at the post method.
Help!
The object passed to POST action is not the same as object passed to the view in GET action. In your POST action you get Semester instance created by MVC using only parameters Request (query string, post data) - that means Student instance is long gone. You will need to pass student ID to POST action and fill it there.
[HttpPost]
public ActionResult Create(Guid studentID, Semester semester)
{
semester.ID = Guid.NewGuid();
semester.CreatedDate = DateTime.Now;
semester.CreatedBy = "ddf";
semester.Student = db.Students.Single(s => s.ID == StudentID);
db.Semesters.AddObject(semester);
db.SaveChanges();
return RedirectToAction("Index", "Student");
}

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