Pass created data to another controller - c#

I am using ASP.NET MVC Entity Framework and I have a page to insert data
public ActionResult Create()
{
return View();
}
// POST: /Home/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="id,firstname,lastname,email,guests,guestfirstname,guestlastname,productInterest,occupancyTimeline,isInvestment,timeSlot,dateSlot")] CP_LC_Preview cp_lc_preview)
{
if (ModelState.IsValid)
{
db.Data.Add(cp_lc_preview);
db.SaveChanges();
return RedirectToAction("Confirm", new { info = cp_lc_preview });
}
return View(cp_lc_preview);
}
What I am trying to do is take that data that was just entered and pass it to another controller to display. like a confirmation page.
Here is my method for the confirm page
public ActionResult Confirm()
{
return View();
}

You may consider following the PRG pattern.
PRG stands for POST - REDIRECT - GET. With this approach,After you successfully save the data, you will issue a redirect response with a unique id in the querystring, using which the second GET action method can query the resource again and return something to the view.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="id,firstname,lastname,email,guests,guestfirstname,guestlastname,productInterest,occupancyTimeline,isInvestment,timeSlot,dateSlot")] CP_LC_Preview cp_lc_preview)
{
if (ModelState.IsValid)
{
db.Data.Add(cp_lc_preview);
db.SaveChanges();
var id = cp_lc_preview.Id;
return RedirectToAction("Confirm", new { id = id });
}
return View(cp_lc_preview);
}
and in your Confirm action method, have id parameter and using the value of that read the record from the db again and use as needed.
public ActionResult Confirm(int id)
{
var d = db.Data.FirstOrDefault(g=>g.Id==id);
// Use d as needed
// to do : Return something
}
TempData
If you do not prefer to have this id in the url, consider using TempData to pass the data. But TempData has a short life span. Once read, the data is gone. TempData uses Session behind the scene to store the data.
TempData["NewItem"] = cp_lc_preview;
return RedirectToAction("Confirm", "controllerName");
and in the Confirm method
public ActionResult actionname()
{
var model=TempData["NewItem"] as CP_LC_Preview
// to do : Return something
}
For your reference
How do I include a model with a RedirectToAction?

You can use TempData for that.
TempData["YourData"] = YourData;//persist data for next request
var myModel=TempData["YourData"] as YourData //consume it on the next request
What is TempData ?
TempData is meant to be a very short-lived instance, and you should only use it
during the current and the subsequent requests only.
Since TempData works this way, you need to know for sure what the next request will be, and
redirecting to another view is the only time you can guarantee this.
Therefore, the only scenario where using TempData will reliably work is when
you are redirecting.This is because a redirect kills the current request , then creates a
new request on the server to serve the redirected view.
Simply said, Asp.Net MVC TempData dictionary is used to share data between
controller actions.
The value of TempData persists until it is read or until the current user’s session times out.
By default, the TempData saves its content to the session state.
TempData values are marked for deletion when you read them. At the end of the request,
any marked values are deleted.
The benefit is that if you have a chain of multiple redirections it won’t cause TempData to
be emptied the values will still be there until you actually use them, then they clear up after
themselves automatically.

Related

Using TempData with Post Redirect Get pattern

There are a number of folks that advocate using TempData with the PRG pattern in .NET Core 2.2.x.
From what I understand, this line of code stores data:
TempData["foo"] = JsonConvert.SerializeObject(model);
And the following reconstitutes the model and then deletes it from the TempData construct:
string s = (string)TempData["Model"];
var model = JsonConvert.DeserializeObject<ModelType>(s);
So given this transient nature of TempData, imagine the following PRG construct. The user POSTs to the UserInfo action, which packages the model into TempData and redirects to a UserInfo GET. The GET UserInfo reconstitutes the model and displays the view.
[HttpPost]
public IActionResult UserInfo(DataCollectionModel model) {
TempData["Model"] = JsonConvert.SerializeObject(model);
return RedirectToAction("UserInfo");
}
[HttpGet]
public IActionResult UserInfo() {
string s = (string)TempData["Model"];
DataCollectionModel model = JsonConvert.DeserializeObject<DataCollectionModel>(s);
return View(model);
}
The user is now on the /Controller/UserInfo page. If the user pressed F5 to refresh the page, the TempData["Model"] would no longer be there and the GET on UserInfo would fail. The fix might be to store the model in TempData after reading it, but wouldn't that result in leaking memory?
Am I missing something?
TempData can be used for storing transient data . It is useful for redirection, when data is needed for more than a single request.When an object in a TempDataDictionary is read, it will be marked for deletion at the end of that request.
That means if you put something on TempData like
TempData["value"] = "someValueForNextRequest";
And on another request you access it, the value will be there but as soon as you read it, the value will be marked for deletion:
//second request, read value and is marked for deletion
object value = TempData["value"];
//third request, value is not there as it was deleted at the end of the second request
TempData["value"] == null
The Peek and Keep methods allow you to read the value without marking it for deletion. Say we get back to the first request where the value was saved to TempData.
With Peek you get the value without marking it for deletion with a single call, see msdn:
//second request, PEEK value so it is not deleted at the end of the request
object value = TempData.Peek("value");
//third request, read value and mark it for deletion
object value = TempData["value"];
With Keep you specify a key that was marked for deletion that you want to keep. Retrieving the object and later on saving it from deletion are 2 different calls. See msdn
//second request, get value marking it from deletion
object value = TempData["value"];
//later on decide to keep it
TempData.Keep("value");
//third request, read value and mark it for deletion
object value = TempData["value"];
You can use Peek when you always want to retain the value for another request. Use Keep when retaining the value depends on additional logic.
Make the following changes in your Get action
public IActionResult UserInfo()
{
//The First method ,
string s = (string)TempData.Peek("Model");
//The Second method
string s = (string)TempData["Model"];
TempData.Keep("Model");
if(s==null)
{
return View();
}
else
{
User model = JsonConvert.DeserializeObject<User>(s);
return View(model);
}
}

Model emptied after returning view

I'm new to ASP and programing in general, so I'm probably doing something fundamentally wrong but here it goes:
Everytime I return a View in my controller the model that I was using in that controller gets emptied. example:
Account acc;
public ActionResult Index()
{
acc = new Account(accountName, password);
return View(acc)
} //At this point there still is a acc object
public ActionResult Edit(string name, string pass)
{
//Here the acc object is null
acc.userName = name;
acc.password = pass;
}
My question would how to acces the account that is currently being used or a way to save the model that was send with de View()
Edit 1
When I tried using TempDate I still encounterd the same problem:
Account acc;
public ActionResult Index()
{
acc = new Account(accountName, password);
TempDate["account"] = acc;
return View(TempDate["account"])
} //TempDate contains 1 object
public ActionResult Edit(string name, string pass)
{
//TempData is empty here
TempDate["account"].userName = name;
TempDate["account"].password = pass;
Return View("Index", TempDate["account"]);
}
Your initial observation when trying to reference acc across two requests happened because ASP.NET creates a new instance of a controller for every request. The GET for Index is one HTTP request; the GET for Edit is a separate HTTP request.
Regarding your first edit to the question, TempData is only valid during the lifetime of a single request. You'll get the same result using it in this scenario. Instead, you should use Session as described in this answer.
The duplicate suggest by Eugene is quite good if you want to try something like Cookie or Session (TempData in MVC)
If you want to store the data on application level you can maintain a collection in static class which can store the data for as long as you want.
You can maintain application level variable also for example Does asp.net MVC have Application variables?

How to use sessions,Tempdata in asp.net mvc4

I am working on asp.net with mvc 4 architectute. Here i have two controller Display and SessionEx. In Display Controller i have an method like below
public ActionResult SessionExample()
{
TempData["FortheFullRequest"] = "FortheFullRequest";
string v = Session["Session1"].ToString();
ViewData["Myval"] = "ControllertoView";
ViewBag.MyVal = "ControllertoView";
Session["Testing1"] = "Testing Session";
return RedirectToAction("SomeOtherAction", "SessionEx");
}
In the SessionEx controller i have the method as below
public ActionResult SomeOtherAction()
{
string str1 = Convert.ToString(Session["Testing1"]);
string str2 = Convert.ToString(TempData["FortheFullRequest"]);
return View();
}
I am debugging the project and i have also used watch to look at the gets stoted in tempdata and session. In the start the appropriate value in both session and tempdata but when the cursor reaches at RedirectToAction method all values gets stored in session and tempdata becomes null.Please help me someone here.
If you want to store data that will be used after a redirect is made to another action method, then use Session.
TempData is mainly for one-time, short-lived, requests as discussed in this this SO question
You are likely finding that the data in TempData is not there after you have redirected to SomeOtherAction(), which is by desing with how TempData works.
To be honest, I never use TempData, I don't see the point myself.

Return to second to last URL in MVC (return View with previous filter conditions applied)?

I'm working on an MVC5 application. On the home screen is a grid allowing users to view Data and be transferred to a number of Views for various actions on each record. One of these is an [EDIT].
The issue I'm encountering is as follows: due to the amount of data it is convenient to Filter the data down (say to a specific location) and then Edit records from there. The filter on this grid (Grid.MVC from CodePlex) performs filtering partially by modifying the URL (http://homeURL/?grid-filter=Location.DEPT__1__accounting) such as 1 being Equals, 2 being Cotains, 3 being StartsWith, and 4 being EndsWith and then after the next 2 underscores being the search criteria.
This functions fine, however upon [POST] return from the Edit the user currently is returned to main Index view without the filtering criteria still set (forcing them to go in over and over and add filtering criteria before performing the similar EDIT on records of the same criteria).
My POST-EDIT method is currently setup to include:
if (ModelState.IsValid)
{
collection.MODIFIED_DATE = DateTime.Now;
collection.MODIFIED_BY = System.Environment.UserName;
db.Entry(collection).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index", "Home");
}
For my attempts I had first thought to return the View with the updated collection (return View(collection)) but this of course just takes me back to the EDIT view, not the home view with the data grid filtered down as previously specified. I considered adding a field in the database, something like LAST_FILTERED_URL, but this just feels like an overgrown band-aid.
Does anyone know of a clean way to go about this?
EDIT:
I had thought to do something similar to Andrea's suggestion early on, but had not thought of doing an explicit redirect with the Parameter of the url-filter passed in the Redirect. Below is my current code for the GET/POST Edit:
// GET: ENITTY_Collection/Edit/5
public async Task<ActionResult> Edit(int id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ENTITY_COLLECTION entity_Collection = await db.ENTITY_COLLECTION.FindAsync(id);
if (entity_Collection == null)
{
return HttpNotFound();
}
// Other code for Controls on the View
return View(entity_Collection);
}
// POST: ENTITY_Collection/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,One_Id,Two_Id,Three_Id,Four_Id,Five_Id,Six_Id,field7,field8,field9,...field18,created_date,created_by,modified_date,modified_by")] ENTITY_COLLECTION entity_Collection)
{
if (ModelState.IsValid)
{
entity_Collection.MODIFIED_DATE = DateTime.Now;
entity_Collection.MODIFIED_BY = System.Environment.UserName;
db.Entry(entity_Collection).State = EntityState.Modified;
await db.SaveChangesAsync();
//return RedirectToAction("Index", "Home");
return View(entity_Collection);
}
// Other code for if Model is Invalid before returning to View.
return View(entity_Collection);
}
I like Andrea's suggestion, but I still need a good way to store the URL the user has when they first navigate to the GET-Edit View, and then use that filtered URL value to return the user to that previous location & filter option when the POST-Edit completes and changes have saved.
Any thoughts?
I'm not sure if this is the most correct way of going about what I'm after, but what appears to be working for me is the use of a Session value.
In my GET method I store the URL:
Session["returnURL"] = Request.UrlReferrer.AbsoluteUri;
Then in my POST I use this value in a Redirect() after saving changes to the record:
var returnURL = (Session["returnURL"] != null) ? Session["returnURL"].ToString() : Url.Action("Index", "Home");
return Redirect(returnURL);
So far all initial testing is resulting in a return to the main view with all sorting/filtering criteria in place before the record was entered into for update.
Have you tried changing passing the current filter to redirect to action as follows?
Note: I am assuming that:
you are redirecting to the same controller
you have a controller parameter called currentFilterValue
RedirectToAction("Index", "Home",new { grid-filter = currentFilterValue });
The default LoginController for an MVC project from Microsoft includes a bunch of methods that use a returnUrl parameter. Using this practice, you could include a return URL when opening the editor, that when editing is done, returns the user back to the prior screen with the filters intact (assuming they are in the URL).
My base class for view models has a property for storing the ReturnURL, which is then stored as a hidden if set.
#Html.HiddenFor(model => model.ReturnUrl)
My action that posts from edit then has this logic:
if (viewModel.ReturnUrl.IsNotNullOrEmptyTrimmed())
{
return RedirectToLocal(viewModel.ReturnUrl, "ActionName", "ControllerName");
}
else
{
// Default hard coded redirect
}
In order to prevent some injections, you will want a validation method (called above) like this for ensuring the URL is valid:
protected ActionResult RedirectToLocal(string returnUrl, string defaultAction, string defaultController)
{
try
{
if (returnUrl.IsNullOrEmptyTrimmed())
return RedirectToAction(defaultAction, defaultController);
if (Url.IsLocalUrl(returnUrl))
return Redirect(returnUrl);
Uri returnUri = new Uri(returnUrl);
if (Url.IsLocalUrl(returnUri.AbsolutePath))
{
return Redirect(returnUrl);
}
}
catch
{
}
return RedirectToAction(defaultAction, defaultController);
}
Hopefully this gets you some ideas and on the right track.

RedirectToAction() destroys string data

Inside my controller I have string variable
private string notificationMessage = "";
which I want to use to copy it's content to ViewBag.Message and display that content on the view.
So inside my edit action I populate it's (notificationMessage) content like this
notificationMessage = "data is succ. updated!";
return RedirectToAction();
But after redirection to Index action this string variable is empty;
How can solve this?
Use TempData instead of ViewBag. It persists between requests.
It is because RedirectToAction returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action. Since HTTP is stateless, you can't simply set something in one action and get it in another(when it is another GET request).
What you can do is
1) pass a querystring to your new action and check that in the next action method and show a message according to that.
return RedirectToAction("ThankYou","Account",new {msg="success"});
and in your ThankYou action
public ActionResult ThankYou(string msg)
{
var vm=YourSuccessViewModel();
if(msg="success") // you may do a null checking before accessing this value
{
vm.Message="Saved Successfully";
}
return View(vm);
}
2) Store in a temporary place like Session / TempData. TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only!
TempData["UserMsg"] = "Saved Successfully";
return RedirectToAction("ThankYou","Account");
and in your ThankYou action you can read it and show to user as needed.
public ActionResult ThankYou(string msg)
{
var msg = TempData["UserMsg"] as string;
//to do : do what you want with the message and return the view.
}
Session object is the backing store for the TempData object, and it is destroyed more quickly than a regular session, i.e., immediately after the subsequent request.

Categories

Resources