Page does not load when pressing back on browser - c#

I have a small project in asp.net core 3.
In one of the razor page I have this:
<form method="post" enctype="multipart/form-data">
<table class="basic">
#for (int i = 0; i < Model.activeSlides.Count; i++)
{
<tr>
<td>
#Model.activeSlides[i].Filename
</td>
<td>
<input type="submit" value="Move Up" asp-page-handler="MoveUp" asp-route-num="#i" />
<input type="submit" value="Move Down" asp-page-handler="MoveDown" asp-route-num="#i" />
<input type="submit" value="Archive" asp-page-handler="Archive" asp-route-num="#i" />
</td>
</tr>
}
</table>
...
</form>
So each of the buttons has their own OnPost function. Each of them modify an XML file and loads the same webpage.
public void OnPostMoveUp(string num)
{
...
}
public void OnPostMoveDown(string num)
{
...
}
public void OnPostArchive(string num)
{
...
}
I have noticed that when the buttons are used, they show the page handler and route in the URL. E.g. https://localhost:44342/screens/edit?num=2&handler=MoveUp
The problem I am facing is after a button has been pressed, the user may select a hyperlink in the first column. This is just an image, but the when the back button on the browser is pressed the page does not load.
P.S. I am not using MVC.

I have fixed this by adding Response.Redirect("/screens/edit"); at the end of all the OnPost methods.
This means the url params don't show therefore then clicking a link and choosing back on the browser now works.
This also fixes refreshing the page so it doesn't submit the form again.

Related

OnClick event is now working on asp net core 6

I have a page that receives data from a database, and for each record it creates a row () on my page. Here is the HTML code:
#foreach (var item in #Model.veterinarios)
{
<tr>
<td>
<span class="custom-checkbox">
<input type="checkbox" id="checkbox1" name="options[]" value="1">
<label for="checkbox1"></label>
</span>
</td>
<td>#item.IdVeterinario</td>
<td>#item.Nombre</td>
<td>#item.Apellido</td>
<td>#item.consultorio</td>
<td>
<i class="material-icons" data-toggle="tooltip" title="Edit"></i>
</i>
</td>
</tr>
}
So the last has two elements that open up a div that is at the end of my code. What i would like to do is to SAVE the #item.IdVeterinario on a variable in my controller (model).
Below is the C# code in the HTML view:
#functions
{
public void guardarIdVet(int a)
{
Model.valor= a;
}
}
When the page runs for the first time, that OnClick event fires 3 times. But when i click on it it doesnt do anything.
I ve tried with asp:LinkButton and still does not work. Funny thing is that yesterday it worked and i changed NOTHING

How to let a button disappear after an action and reappear after another action

i have a code that can allow a button to be visible if some values have been saved to a database or in this case has been bookmarked and becomes visible in the front end if it has been deleted from the database.ie has not been bookmarked
verseModel.Verses = verses;
var bookmarksForCurrentChapter = _context.Bookmarks.Where(x => x.ChapterId == id).ToList();
foreach (var verse in verses)
{
foreach (Bookmark bookmark in bookmarksForCurrentChapter)
{
if (bookmark.VerseId == verse.VerseId)
{
verse.IsBookmarked = true;
}
}
}
This is the code to check for if the values have been bookmarked or saved in the database
#if (!verse.IsBookmarked)
{
<td>
<form asp-action="SaveBookmark" method="post">
<input type="hidden" name="id" value="#verse.VerseId" />
<input type="hidden" name="text" value="#verse.VerseText" />
<input type="hidden" name="chapterid" value="#Model.ChapterId" />
<button class="btn btn-outline-primary btn-sm">Save</button>
</form>
</td>
this is the frontend section that makes the button visible when the values are not bookmarked or saved in the database.
So my question is that i want to be add a delete button to this page so that if the value is bookmarked or saved in the database it becomes visible while the save button disappears and if the value has been deleted from the database from this page or from the database directly the delete button will disappear whiles the save button will reappear
else
{
<td>
<form asp-action = "DeleteBookmark" >
<input type = "hidden" name= "id" value = "#verse.VerseId"/>
<button class = "btn btn-danger btn-sm">Delete</button>
</form>
</td>
}
this is what i attempted to do but the button does not work when clicked and if the values are deleted from the database it does not affect the page at all

MVC razor form with multiple different submit buttons?

A Razor view has 3 buttons inside a form. All button's actions will need form values which are basically values coming input fields.
Every time I click any of buttons it redirected me to default action. Can you please guide how I can submit form to different actions based on button press ?
I really appreciate your time, guidance and help.
You could also try this:
<input type="submit" name="submitbutton1" value="submit1" />
<input type="submit" name="submitbutton2" value="submit2" />
Then in your default function you call the functions you want:
if( Request.Form["submitbutton1"] != null)
{
// Code for function 1
}
else if(Request.Form["submitButton2"] != null )
{
// code for function 2
}
This elegant solution works for number of submit buttons:
#Html.Begin()
{
// Html code here
<input type="submit" name="command" value="submit1" />
<input type="submit" name="command" value="submit2" />
}
And in your controllers' action method accept it as a parameter.
public ActionResult Create(Employee model, string command)
{
if(command.Equals("submit1"))
{
// Call action here...
}
else
{
// Call another action here...
}
}
in the view
<form action="/Controller_name/action" method="Post>
<input type="submit" name="btn1" value="Ok" />
<input type="submit" name="btn1" value="cancel" />
<input type="submit" name="btn1" value="Save" />
</form>
in the action
string str =Request.Params["btn1"];
if(str=="ok"){
}
if(str=="cancel"){
}
if(str=="save"){
}
You can use JS + Ajax.
For example, if you have any button you can say it what it must do on click event.
Here the code:
<input id="btnFilterData" type="button" value="myBtn">
Here your button in html:
in the script section, you need to use this code (This section should be at the end of the document):
<script type="text/javascript">
$('#btnFilterData').click(function () {
myFunc();
});
</script>
And finally, you need to add ajax function (In another script section, which should be placed at the begining of the document):
function myFunc() {
$.ajax({
type: "GET",
contentType: "application/json",
url: "/myController/myFuncOnController",
data: {
//params, which you can pass to yu func
},
success: function(result) {
error: function (errorData) {
}
});
};
This is what worked for me.
formaction="#Url.Action("Edit")"
Snippet :
<input type="submit" formaction="#Url.Action("Edit")" formmethod="post" value="Save" class="btn btn-primary" />
<input type="submit" formaction="#Url.Action("PartialEdit")" formmethod="post" value="Select Type" class="btn btn-primary" />
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit( Quote quote)
{
//code
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PartialEdit(Quote quote)
{
//code
}
Might help some one who wants to have 2 different action methods instead of one method using selectors or using client scripts .
The cleanest solution I've found is as follows:
This example is to perform two very different actions; the basic premise is to use the value to pass data to the action.
In your view:
#using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
if (isOnDli)
{
<button name="removeDli" value="#result.WeNo">Remove From DLI</button>
}
else
{
<button name="performDli" value="#result.WeNo">Perform DLI</button>
}
}
Then in your action:
public ActionResult DliAction(string removeDli, string performDli)
{
if (string.IsNullOrEmpty(performDli))
{
...
}
else if (string.IsNullOrEmpty(removeDli))
{
...
}
return View();
}
This code should be easy to alter in order to achieve variations along the theme, e.g. change the button's name to be the same, then you only need one parameter on the action etc, as can be seen below:
In your view:
#using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
<button name="weNo" value="#result.WeNo">Process This WeNo</button>
<button name="weNo" value="#result.WeNo">Process A Different WeNo This Item</button>
}
Then in your action:
public ActionResult DliAction(string weNo)
{
// Process the weNo...
return View();
}
Try wrapping each button in it's own form in your view.
#using (Html.BeginForm("Action1", "Controller"))
{
<input type="submit" value="Button 1" />
}
#using (Html.BeginForm("Action2", "Controller"))
{
<input type="submit" value="Button 2" />
}
You could use normal buttons(non submit). Use javascript to rewrite (at an 'onclick' event) the form's 'action' attribute to something you want and then submit it. Generate the button using a custom helper(create a file "Helper.cshtml" inside the App_Code folder, at the root of your project) .
#helper SubmitButton(string text, string controller,string action)
{
var uh = new System.Web.Mvc.UrlHelper(Context.Request.RequestContext);
string url = #uh.Action(action, controller, null);
<input type=button onclick="(
function(e)
{
$(e).parent().attr('action', '#url'); //rewrite action url
//create a submit button to be clicked and removed, so that onsubmit is triggered
var form = document.getElementById($(e).parent().attr('id'));
var button = form.ownerDocument.createElement('input');
button.style.display = 'none';
button.type = 'submit';
form.appendChild(button).click();
form.removeChild(button);
}
)(this)" value="#text"/>
}
And then use it as:
#Helpers.SubmitButton("Text for 1st button","ControllerForButton1","ActionForButton1")
#Helpers.SubmitButton("Text for 2nd button","ControllerForButton2","ActionForButton2")
...
Inside your form.
Simplest way is to use the html5 FormAction and FormMethod
<input type="submit"
formaction="Save"
formmethod="post"
value="Save" />
<input type="submit"
formaction="SaveForLatter"
formmethod="post"
value="Save For Latter" />
<input type="submit"
formaction="SaveAndPublish"
formmethod="post"
value="Save And Publish" />
[HttpPost]
public ActionResult Save(CustomerViewModel model) {...}
[HttpPost]
public ActionResult SaveForLatter(CustomerViewModel model){...}
[HttpPost]
public ActionResult SaveAndPublish(CustomerViewModel model){...}
There are many other ways which we can use, see this article ASP.Net MVC multiple submit button use in different ways
As well as #Pablo's answer, for newer versions you can also use the asp-page-handler tag helper.
In the page:
<button asp-page-handler="Action1" type="submit">Action 1</button>
<button asp-page-handler="Action2" type="submit">Action 2</button>
then in the controller:
public async Task OnPostAction1Async() {...}
public async Task OnPostAction2Async() {...}
Didn't see an answer using tag helpers (Core MVC), so here it goes (for a delete action):
On HTML:
<form action="" method="post" role="form">
<table>
#for (var i = 0; i < Model.List.Count(); i++)
{
<tr>
<td>#Model.List[i].ItemDescription</td>
<td>
<input type="submit" value="REMOVE" class="btn btn-xs btn-danger"
asp-controller="ControllerName" asp-action="delete" asp-route-idForDeleteItem="#Model.List[i].idForDeleteItem" />
</td>
</tr>
}
</table>
</form>
On Controller:
[HttpPost("[action]/{idForDeleteItem}"), ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(long idForDeleteItem)
{
///delete with param id goes here
}
Don't forget to use [Route("[controller]")] BEFORE the class declaration - on controller.
Information acquired from:
http://www.codedigest.com/posts/46/multiple-submit-button-in-a-single-form-in-aspnet-mvc
For you chaps coming more recently, you can use the HTML 5 Formaction Attribute.
In your <input> or <button>
Just define:
<button id="btnPatientSubmit" type="submit" class="btn btn-labeled btn-success" formaction="Edit" formmethod="post">
Notice the addition of formation= "Edit", this specifies which ActionResult I want to submit to in my controller.
This will allow you to have multiple submit buttons, where each could submit to independent ActionResults (Methods) in your controller.
This answer will show you that how to work in asp.net with razor, and to control multiple submit button event. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
#{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
In case you're using pure razor, i.e. no MVC controller:
<button name="SubmitForm" value="Hello">Hello</button>
<button name="SubmitForm" value="World">World</button>
#if (IsPost)
{
<p>#Request.Form["SubmitForm"]</p>
}
Clicking each of the buttons should render out Hello and World.

Single click on button not working but double click does the work

Here is my html code
<form runat="server">
Hello, i'm login page
Enter Name <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<input type="submit" value="PressMe" onclick="location.href='<%: Url.Action("EnterLogin", "LoginForm") %>'" />
</form>
Here is my controller code
public class LoginFormController : Controller
{
public ActionResult ShowLogin()
{
return View();
}
public ActionResult EnterLogin()
{
ViewData["Name"] = Convert.ToString(Request.Form["txtName"]);
return View("EnterLogin");
}
}
On clicking PressMe button the expected output is to display Enter Login View but it doesn't.If i double click on the button then it works fine.
Any reason for single click not to work??
The problem is that submit button submits the page. Consider using
<button type="button" onclick="location.href='<%: Url.Action("EnterLogin", "LoginForm") %>'">PressMe</button>
instead of
<input type="submit" value="PressMe" onclick="location.href='<%: Url.Action("EnterLogin", "LoginForm") %>'" />

Generating a POST request for PayPal button in C# ASP.net

I'm trying to allow a web form to use a PayPal buy it now.
The relevant page is here.
Based on which radio button a user selects, depends on which paypal button they are "redirected" to.
The subscriptions are easy - they are just a simple redirect.
The last option, requires a user select a venue.
For this, i require to use the form below:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="10956105">
<table>
<tr><td><input type="hidden" name="on0" value="Venue">Venue</td></tr><tr><td>
<input type="text" name="os0" maxlength="60"></td></tr>
</table>
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
But of course, I want to do it without using that form.
What I have so far is:
if (singleOneOff.Checked)
{
paypalForm.Text = getPaypalForm(venueSelect.SelectedItem.Text);
var strJS = getPayPalPostJS("_xclick");
paypalJs.Text = strJS;
var xxx = "dd";
}
This determines if that particular radio button was ticked.
getPaypalForm
private String getPaypalForm(string venue)
{
StringBuilder strForm = new StringBuilder();
strForm.Append(#"<form action=""https://www.paypal.com/cgi-bin/webscr"" name=""_xclick"" method=""post"">");
strForm.Append(#"<input type=""hidden"" name=""cmd"" value=""_s-xclick"">");
strForm.Append(#"<input type=""hidden"" name=""hosted_button_id"" value=""10956105"">");
strForm.Append(#"<input type=""hidden"" name=""on0"" value=""Venue"">");
strForm.Append(#"<input type=""text"" name=""os0"" value=""{0}"" maxlength=""60"">");
strForm.Append("</form>");
return String.Format(strForm.ToString(), venue);
}
getPayPalPostJS
private String getPayPalPostJS(string strFormId)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var paypalForm = document.forms.namedItem('{0}');");
strScript.Append("paypalForm.submit();");
strScript.Append("</script>");
return String.Format(strScript.ToString(), strFormId);
}
However, if i select the radio button, and a venue, and press the button, nothing happens....
Any ideas where i've gone wrong?
I followed this guide: http://www.netomatix.com/development/postrequestform.aspx
Here's a much cleaner, server-side solution to the ASP.NET/PayPal single form problem:
http://codersbarn.com/post/2008/03/08/Solution-to-ASPNET-Form-PayPal-Problem.aspx
The root of the problem is that ASP.Net web forms wrap everything on the page inside of one large <form> tag. Your paypal code is rendering a nested form and that doesn't work.
Read this question for more information.

Categories