C# MVC ActionLink clear session before reloading page - c#

I have a simple form page, where user can fill some data. After I press post, I need all that data to remain as it is, so if user wants to change data, he/she can. After I save data I store Client object in Session and every time I press Save button, I check if there is user already in Session.
Now I have #Html.ActionLink("New client", "NewUser");, that I press, when I want to create new user. So this link would reload the page and clear that Session.
Note that "New user" should redirect to Index instead, but I managed to get it to work like that, but is not valid way to do so.
Controller code:
public ActionResult Index()
{
return View(_vm);
}
public ActionResult NewUser()
{
Session["newClient"] = null;
return RedirectToAction("Index");
}

clearing the session can only done on backend so you have to make action to clear the session but you dont need return RedirectToAction("Index"); instead return the view
public ActionResult NewUser()
{
Session["newClient"] = null;
return View("Index",_vm);
}
since you are redirecting to the index view for creating new user

Related

Pass created data to another controller

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.

using text box value in different action with same controller in mvc5

I am new to mvc5,
i want to use the value of text box from login view in different action in the same controller,
all the example i seen take the value to one action using BeginForm()
is there is any way to do that?
the login view:
and i want to perform this action:
I am try to use TempData but it return empty page
1:
I do not understand what your exact requirement is. However BeginForm() has many overloads. like BeginForm(actionName, conttrollername). If you simply want to post the data to different action method then you may use this overload
#Html.BeginForm(actionName, conttrollername)
I Understand you difficult question. You want to use data provided by login in another action to render another page.
Use this:
[HttpPost]
public ActionResult ConfirmRegistration(string username, string password)
{
try
{
DoRegistration(username, password);
//automatically login user after registration
FormsAuthentication.SetAuthCookie(user.UserName, user.RememberMe);
//after successful login, redirect to UserPage and render UserPage page
return RedirectToAction("UserPage", new{username = username, password = password});
}
catch(YourLoginFailedExceptioOrWhatEver)
{
return View(username); //login failed, go back to login page
}
}
public ActionResult UserPage(string username, string password)
{
.......
return View(information);
}

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.

Form submmited twice from MVC Controller Action

I am trying to explain why a user was able to submit the same form details twice. At first, I was thinking that the submit button was pushed twice, this may still be the case.
When I checked the results in the database, I can see the same information has been entered twice, but also the same datetime stamp has been entered, down to the second. Surely it takes at least another second to push submit again if this is the case.
In addition after the survey is inputted and saved the user is redirected to a different page.
Why does this happen?
[HttpPost]
public ActionResult InputResult(SurveyViewModel model)
{
if (ModelState.IsValid)
{
Survey_Result InputResult = new Survey_Result();
InputResult.SurveyStatusID = model.SurveyStatusID;
InputResult.Q1DateCompleted = DateTime.Now;
InputResult.Q2 = model.Q2;
InputResult.Q3 = model.Q3;
InputResult.Q10 = model.Q10;
InputResult.Q11 = model.Q11;
InputResult.Q11Other = model.Q11Other;
InputResult.DateAdded = DateTime.Now;
InputResult.AddedBy = Convert.ToInt32(User.Identity.GetUserId());
_surveyService.AddSurvey(InputResult);
_surveyService.Save();
return RedirectToAction("Details", "Survey", new { id = model.SurveyStatusID, feedback = "InputComplete" });
}
return RedirectToAction("Details", "Survey", new { id = model.SurveyStatusID, feedback = "InputError" });
}
The code looks fine to me. If you have access to the user, you could pop Fiddler on it to see if it is posting data twice. If it doesn't happen all the time then its almost certainly user error IMHO.
If you don't have access to the client you could pop in a log entry on each post request or debug line if you are in a position to collect it on this server.
I had similar issues and client side javascript to disable the button on click did the trick for me.
Are you sure you need both AddSurvey and Save?
Remove save and retry.

Cookies logout razor remove

I have an asp application and i need to remove all current session's cookies in the action of logout:
public ActionResult Logout()
{
Upload.Models.CompteModels.Connected = false;
return RedirectToAction("Login", "Account");
}
Now i use a static class CompteModels with a boolean to test if the user is authentifying or not but it's not efficent. so i think that i have to remove all cookies when i logout.
How can i do it?
A static property is shared across all users, so using a static property to determine if a user is logged in will not work correctly, as this would log out all users, or log them in.
You can abandon the session using Session.Abandon or remove a cookie using the HttpResponse.Cookies collection, and write a cookie to it that is expired.
If you mean drop session data and remove the sessions cookies see here for how to do it.
You could create a session variable called LoggedIn or something similar and just clear this in your logout action. Then in your Login action you need to check for this session.
public ActionResult Logout()
{
Upload.Models.CompteModels.Connected = false;
Session.Remove("LoggedIn");
return RedirectToAction("Login", "Account");
}
public ActionResult Login()
{
// check for session var, redirect to landing page maybe?
if(Session["LoggedIn"] == null)
{
RedirectToAction("Home", "Index");
}
else
{
Session.Add("LoggedIn", true);
}
return RedirectToAction("TargetPage", "TargetAction");
}
Just one idea, depends on where you want users to be redirected to and such, TargetPage could be an admin area or something similar.

Categories

Resources