Checkbox retains state after postback - asp.net

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

Related

Updating records on different tables ASP.NET MVC

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

Hot to Add Include DropDown List in ASP.net in my code below. I want to Include foreign table Item Location to my Item table

Below is my HTTP GET and HTTP POST Codes. I want to add .Include Item Location for my drop down list. Please help identity where I can add the Include for my Item Location on below code. Thank you!
Below Is my HTTPGET Method...
[HttpGet]
public ActionResult AddOrEditItem(int id = 0)
{
Item item = new Item();
if (id != 0)
{
using (erpdb db = new erpdb ())
{
item = db.Items.Where(x => x.ItemId == id).FirstOrDefault<Item>();
}
}
return View(item);
}
Below Is my HTTPPOST Method
[HttpPost]
public ActionResult AddOrEditItem(Item item)
{
try
{
using (erpdb = new erpdb())
{
if (item.ItemId == 0)
{
db.Items.Add(item);
db.SaveChanges();
}
else
{
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
}
}
return Json(new { success = true, html = GlobalClass.RenderRazorViewToString(this, "ViewAllItems", GetAllItems()), message = "Submitted Successfully" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
Please help how can I add my Item Location so that it can be selected on my dropdownlist view and as well as saved
I was able to solve my own issue myself by doing the following:
Step 1: Creating a viewmodel for items so that I can include item location on my form
Step 2: added .Include when calling the database so that I can include it to my indes view of items

ASP.NET MVC - Session Variables are null in Callback from server ActionResult method

I am implementing CoinPayments IPN in my application and I have trouble with passing data to the method that take their Callback. I have tried like everything I could find: TempData, SessionVariables, tried to implement it somewhere in forms and maybe Request it but that didn`t work for me. So I also tried to implement it with Global static variables. And it worked! But then came another issue: if more than one user were to buy something from website at the same time or even in between any callbacks their data will get mixed. So here I am, trying again to make Session Variables work and have no clue why they are not working as I used them before. Probably what I can think of is that because its a callback from CoinPayments and I handle something wrongly.
Here is the code I have right now: Tho I tried different variations like implementing Session in Get Payment method. Now I ended up with it and it still comes out as null in POST METHOD.
Class for handling Session Variables:
public static class MyGlobalVariables
{
public static int TokenChoice
{
get
{
if (System.Web.HttpContext.Current.Session["TokenChoice"] == null)
{
return -1;
}
else
{
return (int)System.Web.HttpContext.Current.Session["TokenChoice"];
}
}
set
{
System.Web.HttpContext.Current.Session["TokenChoice"] = value;
}
}
public static int PaymentChoice
{
get
{
if (System.Web.HttpContext.Current.Session["PaymentChoice"] == null)
{
return -1;
}
else
{
return (int)System.Web.HttpContext.Current.Session["PaymentChoice"];
}
}
set
{
System.Web.HttpContext.Current.Session["PaymentChoice"] = value;
}
}
public static string CurrentUser
{
get
{
System.Web.HttpContext.Current.Session["CurrentUser"] = System.Web.HttpContext.Current.User.Identity.Name;
return (string)System.Web.HttpContext.Current.Session["CurrentUser"];
}
}
}
Class that returns view where you click on CoinPayments button:
public ActionResult Payment(int tokenChoice, int paymentChoice)
{
ViewBag.Payment = paymentChoice;
MyGlobalVariables.PaymentChoice = paymentChoice;
MyGlobalVariables.TokenChoice = tokenChoice;
return View();
}
Callback class that handles Callback from CoinPayments:
[HttpPost]
public ActionResult Payment()
{
NameValueCollection nvc = Request.Form;
var merchant_id = id;
var ipn_secret = secret;
var order_total = MyGlobalVariables.PaymentChoice;
if (String.IsNullOrEmpty(nvc["ipn_mode"]) || nvc["ipn_mode"] != "hmac")
{
Trace.WriteLine("IPN Mode is not HMAC");
return View();
}
if (String.IsNullOrEmpty(HTTP_HMAC))
{
Trace.WriteLine("No HMAC signature sent");
return View();
}
if (String.IsNullOrEmpty(nvc["merchant"]) || nvc["merchant"] != merchant_id.Trim())
{
Trace.WriteLine("No or incorrect Merchant ID passed");
return View();
}
//var hmac = hash_hmac("sha512", request, ipn_secret.Trim());
var txn_id = nvc["txn_id"];
var item_name = nvc["item_name"];
var item_number = nvc["item_number"];
var amount1 = nvc["amount1"];
var amount2 = float.Parse(nvc["amount2"], CultureInfo.InvariantCulture.NumberFormat);
var currency1 = nvc["currency1"];
var currency2 = nvc["currency2"];
var status = Convert.ToInt32(nvc["status"]);
var status_text = nvc["status_text"];
Trace.WriteLine(status);
if (currency1 != "USD") {
Trace.WriteLine("Original currency mismatch!");
return View();
}
if (Convert.ToInt32(amount1) < Convert.ToInt32(order_total))
{
Trace.WriteLine("Amount is less than order total!");
return View();
}
if (status >= 100 || status == 2) {
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var account = dc.Users.Where(a => a.Username == MyGlobalVariables.CurrentUser).FirstOrDefault();
if (account != null && account.Paid == 0)
{
Trace.WriteLine("Payment Completed");
Trace.WriteLine("Tokens to add: " + MyGlobalVariables.TokenChoice);
account.Tokens += MyGlobalVariables.TokenChoice;
account.Paid = 1;
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
}
}
} else if (status < 0)
{
Trace.WriteLine(
"payment error, this is usually final but payments will sometimes be reopened if there was no exchange rate conversion or with seller consent");
} else {
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var account = dc.Users.Where(a => a.Username == MyGlobalVariables.CurrentUser).FirstOrDefault();
if (account != null)
{
account.Paid = 0;
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
}
}
Trace.WriteLine("Payment is pending");
}
return View();
}
As you can see there are only 3 variables I need to handle.
Also someone might ask why I use Session Variable for Current.User?
Well for some reason Callback method can not read Current.User as it return null. And well... nothing really changed as for now.
If you have ever experienced something like that or can find an issue I would be so thankful since I wasted already over 2 days on that issue.
EDIT:
After some testing I found out variables works fine if I run Post method on my own. So the problem is with handling callback from CoinPayments. Is there a specific way to deal with this?

Cannot post update to database. not all code paths return a value

[HttpPost]
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
return View(user);
}
}
I keep on getting an error while saving data to the database.
UpdateDetail worked while retrieving message, but i keep getting error when saving.
Your issue is if your ModelState.IsValid == false, then you are not returning anything. I put a comment in code below where it is.
Depending on what your logic needs to do, would determine what needs to be returned if IsValid == false
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
// this is your issue, this needs to be outisde the if statement, or you have to do an else and return null (or whatever you need to based off your logic)
return View(user);
}
}
Keep return statement outside of If statement. this would fix your error.If model is valid model updated with user details from database will be pushed to View. other wise same user model will be pushed to the view.
[HttpPost]
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
}
return View(user);
}

Save data instead of adding to database

I'm trying to edit an article in my asp.net mvc project. This is what I do when I create a project:
public ActionResult Create(ArticleViewModel model)
{
if (ModelState.IsValid)
{
try
{
// Get the userID who created the article
User usr = userrepo.FindByUsername(User.Identity.Name);
model.UsernameID = usr.user_id;
repository.AddArticle(model.Title, model.Description, model.ArticleBody);
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
return RedirectToAction("Index");
}
return View(model);
}
In my repository:
public void AddArticle(string Title, string Description, string ArticleBody)
{
item Item = new item()
{
item_title = Title,
item_description = Description,
article_body = ArticleBody,
item_createddate = DateTime.Now,
item_approved = false,
user_id = 1,
district_id = 2,
link = "",
type = GetType("Article")
};
try
{
AddItem(Item);
}
catch (ArgumentException ae)
{
throw ae;
}
catch (Exception)
{
throw new ArgumentException("The authentication provider returned an error. Please verify your entry and try again. " +
"If the problem persists, please contact your system administrator.");
}
Save();
// Immediately persist the User data
}
public void AddItem(item item)
{
entities.items.Add(item);
}
But now I want to edit an article, this is what I have till now:
public ActionResult Edit(int id)
{
var model = repository.GetArticleDetails(id);
return View(model.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ArticleViewModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the User
try
{
item Item = repository.GetArticleDetailsByTitle(model.Title);
Item.item_title = model.Title;
Item.item_description = model.Description;
Item.article_body = model.ArticleBody.
// HERE I NEED TO SAVE THE NEW DATA
return RedirectToAction("Index", "Home");
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
As you can see I check the adjusted text and drop it in "Item". But how can I save this in my database? (the function in my repository)
I think your save() method had entityobject.SaveChanches()
So you want to call that save() method in here
try
{
item Item = repository.GetArticleDetailsByTitle(model.Title);
Item.item_title = model.Title;
Item.item_description = model.Description;
Item.article_body = model.ArticleBody.
**Save();**
return RedirectToAction("Index", "Home");
}
should be need to only Save() method, could not need to AddItem() method .
I'm afraid you'll need to get article again from database, update it and save changes. Entity framework automatically tracks changes to entites so in your repository should be:
public void EditArticle(Item article)
{
var dbArticle = entities.items.FirstOrDefault(x => x.Id == article.Id);
dbArticle.item_title = article.item_title;
//and so on
//this is what you call at the end
entities.SaveChanges();
}

Resources