Updating records on different tables ASP.NET MVC - asp.net

In my application from the view someone pressed the Approve button, controller will collect the Main Id of the request. Here I want to update 3rd table Approval_Status column to true. I passed the main Id and got the 3rd table Id which I want to update record to the variable.
int PartyId = db.ApprovalProcess.Where(x => x.Req_Id == id).ToList().First().Id;
and then I wrote this code to pass the value. But it wont work. Can I get a help for this (question will seems like easy to you, but i want to tell you that I'm self learning ASP.NET MVC these days. So some stuff still I couldn't get)
Here is my database structure. Main table name is AppRequest, 2nd table is ApprovalProcess and the 3rd one is Approval_Parties.
This is my current code:
public ActionResult ApproveRequest(int? id)
{
int PartyId = db.ApprovalProcess.Where(x => x.Req_Id == id).ToList().First().Id;
if (ModelState.IsValid)
{
// model.Approved_Date = DateTime.Now;
ApprovalParty approvalParty = new ApprovalParty();
approvalParty.Approve_Status = true;
db.SaveChanges();
return RedirectToAction("Index");
}
}
I think I'm missing the code that which record should update in the table that already assigned that Id to the PartyId.

Something like this would work:
public ActionResult ApproveRequest(int? id)
{
ApprovalProcess approvalProcess = db.ApprovalProcess.FirsOrDefault(x => x.Req_Id == id);
if (approvalProcess != null)
{
ApprovalParty approvalParty = db.Approval_Parties.FirsOrDefault(x => x.ApprovalProcess_Id == approvalProcess.Id);
if (approvalParty != null)
{
approvalParty.Approve_Status = true;
approvalParty.Approved_Date = DateTime.Now;
db.SaveChanges();
return RedirectToAction("Index");
}
}
}

Related

Saving current user name(logged) into Form database ASP.Net MVC

I am newbie in ASP.NET. Is there a possible way to save the current logged user into the form database when the form is submitted?
(i.e) When multiple registered users enter a form and click save their user name is saved into the contents of form database.
I had googled it but couldn't find related topics (maybe I used the wrong keywords). If methods are available kindly suggest link.
[Edit]
I have used asp.net identity for authentication.
My current code for save
public ActionResult NewPR()
{
var depts = _context.Depts.ToList();
var currencytypes = _context.Currencytypes.ToList();
var viewModel = new NewPRViewModel
{
PRview = new PRview(),
Currencytypes = currencytypes,
};
return View("NewPR", viewModel);
}
[HttpPost]
public ActionResult Save(PRview prview)
{
if (!ModelState.IsValid)
{
var viewModel = new NewPRViewModel
{
PRview = prview,
Currencytypes = _context.Currencytypes.ToList()
};
return View("NewPR", viewModel);
}
if (prview.Id == 0)
_context.PRviews.Add(prview);
else
{
var prviewInDb = _context.PRviews.Single(c => c.Id == prview.Id);
prviewInDb.SupplierName = prview.SupplierName;
prviewInDb.Brand = prview.Brand;
prviewInDb.Qty = prview.Qty;
prviewInDb.Unitprice = prview.Unitprice;
}
_context.SaveChanges();
return RedirectToAction("Index", "PRview");
}

Debugging Optimistic Concurrency with AJAX Call

I'm currently having a problem with optimistic concurrency in my ASP.NET MVC application.
Essentially, this following controller works fine when called upon once. However, I have a page that is made to modify residents in six different groups at the same time. This is where the problem occurs. Basically, I post up the list of residents one at a time for each list so there are essentially six concurrent ajax calls that hit the server at the same time. (This may be what I need to change, but I am not sure!)
The javascript ajax call posts up the id of the group along with a list of the resident IDs. The residents are then added to the groups references. I have been looking into refreshing the state, but this isn't working as it seems only one of the six groups is updated. I have tried also letting the client win. I really just need some guidance and tips on resolving this issue!
Here is my current code in my controller:
var group = _context.TherapyGroups.Include(r => r.Residents)
.Where(x => x.ID.ToString() == groupid).FirstOrDefault();
if(group == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
group.Residents.Clear();
foreach(var id in residents)
{
var resident = _context.Residents.Where(x => x.ID.ToString() == id).FirstOrDefault();
if(resident == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
group.Residents.Add(resident);
}
bool saveFailed;
do
{
saveFailed = false;
try
{
_context.SaveChanges();
}
catch (DbUpdateException e)
{
saveFailed = true;
((IObjectContextAdapter)_context).ObjectContext.Refresh(RefreshMode.StoreWins, _context.Residents);
}
} while (saveFailed);
Wasn't sure how to fix the issue you are having with the code you have, so tried simplifying it a bit. See if this helps:
var groupId = _context.TherapyGroups.FirstOrDefault(x => x.ID.ToString() == groupid).Select(x => x.ID);
if(groupId == "") // or if(groupId == 0), not sure type of x.ID
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
// Get all of the residents whose Id is in the residents list
var residentObjects = _context.Residents.Where(x => residents.Contains( x.ID.ToString()));
// Update the groupId for each resident
foreach(var resident in residentObjects)
{
resident.GroupId = groupId;
}
var saveFailed = false;
try
{
_context.SaveChanges();
}
catch (DbUpdateException e)
{
saveFailed = true;
}

Checkbox retains state after postback

how come my model retains the state? why is it like this?
Isn't it supposed to be refreshed since i am trying to send a brand new instance of the model?
Here is an example:
If i delete anything on the middle, after postback, the checkbox will still be checked
Here are my codes:
Here is my postback code:
[HttpPost]
public ActionResult Index(IEnumerable<Employee> emp)
{
EmployeeContext test = new EmployeeContext();
if (emp.Count(x => x.selected) == 0)
{
return View(test.Employees);
}
else
{
foreach (Employee del in emp)
{
if (del.selected)
{
Employee dummy = test.Employees.Single(x => x.id == del.id);
test.Employees.Remove(dummy);
test.SaveChanges();
}
}
return View(test.Employees);
}
}
What should i do to remove that state? i read something about ModelState.Remove so my idea is that use a loop to clear each of my checkboxes but i am not sure if that will be good when it comes to performance. What should i do?
Fixed by changing them to Redirect:
[HttpPost]
public ActionResult Index(IEnumerable<Employee> emp)
{
EmployeeContext test = new EmployeeContext();
if (emp.Count(x => x.selected) == 0)
{
return RedirectToAction("Index");
}
else
{
foreach (Employee del in emp)
{
if (del.selected)
{
Employee dummy = test.Employees.Single(x => x.id == del.id);
test.Employees.Remove(dummy);
test.SaveChanges();
}
}
return RedirectToAction("Index");
}
}
Full Credits to : Stephen Muecke for the PRG pattern.
if you didn't want model state keep it's value in the view, you don't need to pass the model into the view
just change this
return View(test.Employees);
into
return View();

Change State to EntityState.Modified raised error

I have the following Asp.Net MVC 4 scaffold code.
//
// POST: /Detail/Edit/5
[HttpPost]
public ActionResult Edit(Detail detail)
{
var dd = Details.FirstOrDefault(d => d.DetailId == detail.DetailId);
if (dd == null)
{
return HttpNotFound();
}
detail.UpdatedBy = User.Identity.Name;
detail.UpdateTime = DateTime.Now;
if (ModelState.IsValid)
{
_db.Entry(detail).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index", new { id = detail.MasterId });
}
return View(dealDetail);
}
However, the line _db.Entry(detail).State = EntityState.Modified; raise the following error. What's the correct way to update the detail line of a master/detail editing scenery?
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
This line:
var dd = Details.FirstOrDefault(d => d.DetailId == detail.DetailId);
will cause loading of Detail entity from the database. Now you have two Details with the same Id but only one (the one loaded by that query) can be used for persistence. You can change your code to:
if (!Details.Any(d => d.DetailId == detail.DetailId))
{
return HttpNotFound();
}
or update the attached detail (dd) for example by:
// All values of detail entity must be set in your HTTP post!
_db.Entry(dd).CurrentValues.SetValues(detail);

ASP.NET MVC create a new database record

I've been learning asp.net mvc 3. So, basically I'm trying to create a new record in database. However, I'm trying to keep a particular record predefined
public ActionResult Create()
{
var dc = new ServicesDataContext();
var model = new Maping();
var query = (from m in dc.Customers
where m.CustomerId == model.CustomerID
select m.CustomerId);
ViewData["CustomerID"] = query.First();
return View(model);
}
//
// POST: /Customerservice/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="CustomerServiceMappingID")] Maping serviceToCreate, FormCollection form)
{
if (!ModelState.IsValid)
return View();
var dc = new ServicesDataContext();
dc.Mapings.InsertOnSubmit(serviceToCreate);
try
{
dc.SubmitChanges();
}
catch (Exception e)
{
}
try
{
var id = Int32.Parse(form["CustomerID"]);
ViewData["CustomerID"] = id;
return RedirectToAction("Index", new { id = id });
}
catch
{
return RedirectToAction("INDEX", "Home");
}
}
So this is what I did. So, the case is that id value in second action method is what i needed. However the second method gets redirectd to index so viewdata value is lost.And the thing i did in the first crate method is wrong because no value is assigned. So, can u please help me with this problem.
Use TempData, not ViewData - it will be valid until it is read again. Also why are you adding it into viewdata when it is being passed as a parameter in the RedirectToAction?

Resources