using text box value in different action with same controller in mvc5 - c#

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

Related

How can I make a return with parameters in a View c# asp .net mvc?

Sorry for the title, but don't know how to explain it. (.NET ASP MVC)
So what I'm trying is to create a payment request via TripleA API(redirect on their page), if the payment is successful, they will redirect on my success page with some parameters, how can I handle those parameters?
What I've tried:
public IActionResult ErrorPage(string payment_reference, string status)
{
return View(payment_reference,status);
}
https://developers.triple-a.io/docs/triplea-api-doc/dd286311a5afc-make-a-payment-request
(scroll down to success_url for more info)
To expand on Steve's comment, create a record (less code than a class) as follows...
public record ErrorViewModel(string PaymentReference, string Status);
...then use this when you send data to the view...
public IActionResult ErrorPage(string payment_reference, string status)
{
return View(new ErrorViewModel(payment_reference,status));
}
You'll need to update your view to have the following line at the top...
#model ErrorViewModel
That should be all you need.
Based on the documentation, you expect a request like this,
https://www.myshop.com/payment-success?status=paid&payment_reference=ASDDF...&order_currency=USD&order_amount=10
And you translate that into a controller method,
[HttpGet("payment-success")]
public IActionResult ResultPage(string payment_reference, string status, string order_currency, decimal order_amount)
{
var result = new ResultViewModel(payment_reference,status, order_currency, order_amount);
return View(result);
}
I also noticed that the doc says,
Note: This field is required if integrating using External URL Payment Form. For other integrations, either insert the field with a url, or remove the field completely.
So if you use External URL Payment Form integration, then I don't think you will be able to get the status and reference.
The same applies for cancel_url.

C# MVC ActionLink clear session before reloading page

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

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.

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.

Asp.Net Mvc - Don't clear error input in form

When I validate a form with Asp.Net Mvc and there's an error on the form, Asp.Net return me the form with the correct error message but clear the content of the input. I would like the content of the input to stay even if this content is wrong. How can I do that ?
UPDATE
Maybe this is because I don't use the default validation. I use the Fluent Validation library.
Here what I do :
var validator = new UserValidator();
var results = validator.Validate(user);
results.AddToModelState(ModelState, "");
if (!ModelState.IsValid)
{
return View("SignUp", user);
}
The problem might be in how you "bind" the model you are passing in the view. If you use a strongly typed view and create the input fields with for example
<%=Html.TexboxFor(m=>m.UserName)%>
or
<%=Html.TextBox("UserName", Model.UserName)%>
then you should see the values after posting.
Regards
In addition to what #Germán Ubillos posted, you can also store the post values in TempData and send them back through.
<%=Html.TextBox("UserName", TempData["UserName"])%>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SomeAction(string UserName)
{
TempData["UserName"] = UserName;
// Do your validation
var validator = new UserValidator();
var results = validator.Validate(user);
results.AddToModelState(ModelState, "");
if (!ModelState.IsValid)
{
return View("SignUp", user);
}
//return some view
}

Categories

Resources