Hey everyone, I am playing around with ASP.NET MVC and Entity Framework. I was wondering what is the best way to deal with passing around data from controllers to views and then back. I will explain a little better:
I have an action that is for creating a new "Receipt" object
[Authorize]
public ActionResult CreateReceipt(int id)
{
//I create the receipt object
Receipt newReceipt = new Receipt();
// assign some information about the owner of the receipt
// and the group that it belongs to
newReceipt.Group = group;
newReceipt.Owner = user;
//send off to the view to be displayed
return View(newReceipt);
}
So I basically create a receipt and pre-fill in some information (including the authorized user and some group ID information) I can then send that to a view with all sorts of form elements that let the user fill in the other missing fields and submit so that a new receipt is added. This all works great if all the fields from the receipt object are being displayed on the form.
If I remove the form elements for things that the user shouldn't be touching (such as the group number, the user id that the receipt belongs to, etc...) Then when I submit the form and pick it up in the controller:
[HttpPost]
[Authorize]
public ActionResult CreateReceipt(Receipt receipt)
{
if (ModelState.IsValid)
{
using (EntityFrameworkEntities context = new EntityFrameworkEntities)
{
context.AddToReceipts(receipt);
context.SaveChanges();
}
return RedirectToAction("Index");
}
return View(receipt);
}
Then all that handy preloaded information that I filled in and sent to the view doesn't come back with the post. I know I could place the UserID or the GroupID into a hidden field and then it makes it back with the POST, but that feels wrong. Technically someone could go in, change the hidden values and resubmit the post. I could then do checking to make sure that everything should be where it belongs, but that also feel like another trip to the database to get information that I already got once.
If anyone can elaborate a bit on what the standard way of passing data around from model to view to controller, that would be great. Thank you for your time and help!
If you're worried about someone monkeying with hidden field values to affect other records, pad the ID value and encrypt it in the hidden field, then decrypt on postback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With