How to prevent re-submit of form when getting back to it? - html

I have some regular input webpage where users type in some details about item.
Then after the user presses the submit button she is redirected to a webpage saying that everything went fine. The problem is that if she clicks the back button then the input page is displayed again, and if she hits the sumbit, the form is re-submitted and another item is being written to the database, which is not desirable, of course.
I'm using ASP.NET MVC in C#. What is the best-practice way to deal with this situation?

You can create a hidden form element that marks the form as unique. Each time the form is written by the server, create a new random unique value. When the form is submitted, have the server check that the identifier has not been used before.
The problem is if you want to allow the user to press back and re-submit to create a second entry, there is no way to tell if the user intended to make a second copy or not. What you could do in this situation is make a link which takes the user to the same form, but with a newly generated hidden form element containing the unique identifier.

You can use TempDate and a hidden form value to both store a unique token, and compare them on the postback.
Like this:
public ActionResult FormDemo()
{
var guid = Guid.NewGuid().ToString();
ViewData.Model = guid;
TempData.Add("guid", guid);
return View();
}
[HttpPost]
public ActionResult FormDemo(string name, string guid)
{
if(guid != (string)TempData["guid"]) return new HttpStatusCodeResult(500);
return RedirectToAction("FormDemoReceipt");
}
public ActionResult FormDemoReceipt()
{
return Content("Form submitted OK!");
}
My FormDemo view looks like this:
#using (Html.BeginForm())
{
#Html.Hidden("guid", Model)
#Html.TextBox("name");
<input type="submit"/>
}

Related

Add #id suffix to RedirectToAction() in controller ASP NET MVC

Somehow I find this hard to describe, but here I go:
I have a div in my SelectClasses Razor view page with an id="id152".
In order for me to show that div on the page at reload, I have to add the suffix #id152 to my page url.
<div id="id152">blabla</div>
...
..
Section 7
Now my question: Is there a way to add/pass this suffix to a 'RedirectToAction()'?
public ActionResult Index()
{
//All we want to do is redirect to the class selection page and add a suffix
return RedirectToAction("SelectClasses", "Registration", new { id = 99 })); //add suffix here somewhere
}
So when my SelectClasses view is shown, the url looks something like this:
'[url]/SelectClasses/99#id152'
The RedirectToActionResult (among the rest of RedirectTo* results) is meant to be used for generation of URLs based on registered routing data.
In your case, you wish to concatenate a hash parameter value (#id152) that is not being sent to the server and only used by the browser. That's why said methods don't bother dealing with it.
I suggest you do this instead:
var redirUrl = Url.Action("SelectClasses", "Registration", new { id = 99 });
redirUrl = String.Concat(redirUrl, "#id152");
return Redirect(redirUrl);

Only one type of action can execute?

I going to show my problem with an example:
I have a button. When clicked, it creates a mail draft based on the TextInputFields in the add-on.
I have a validate function, which can say if the fields filled right or not.
If I want to notify the user somehow about the wrong fields, I have to create a notify or rebuild the card with error information. These actions can be returned in a normal Action, but not with a composeAction (because composeAction has to return with builded draft), so I have to register a composeAction and a simple action to the button.
When I clicked this kind of button, only one of the action execute and the other do nothing.
Some code about how I tried to implement:
section.addWidget(CardService.newTextButton()
.setText('Validate and Create')
.setComposeAction(CardService.newAction().setFunction('doIt'), CardService.ComposedEmailType.STANDALONE_DRAFT)
.setOnClickAction(CardService.newAction().setFunction('notify')));
ActionFunctions:
function doIt(event){
validate the event['formInput'] object;
if(valid the formInput)
create andr return the draft;
else
return null;
}
function notify(event){
validate the event['formInput'] object;
if(valid the formInput)
return null;
else
return notify or rebuilded card with error info;
}
Mostly the simple action run, and the compose do nothing. If I place Logger.log() functions in the callback function, only one appears on api log.
Anyone have tried before validate and create draft at the same click?
How about this:
var action=CardService.newAction().setFunctionName('myFunction');
var validateCreateButton=CardService.newTextButton()
.setText('Validate & Create')
.setOnClickAction(action);
section.addWidget(validateCreateButton);
function myFunction(e) {
doit(e);
notify(e);
}

How To Pass Dynamically created value into another page..?

i am dynamically create contents and buttons into my code behind "tree.aspx.cs" page
sbmainTbl.AppendFormat("<tr><td><div class=\"a\">{0}<div class=\"details\"<p id=\"p\">{1}</p><ul><li>Parent-UnitId:{2}</li><li>Address :{3}</li><li>City: {4}</li><li>EmailId: {5}</li><li>PhoneNo: {6}</li><li>FaxNo: {7}</li><li><input type=\"button\" value=\"ADD\" onclick=\"f2();\" /></li></ul></div></div></div></td></tr>",
CellText(dtparent.Rows[0]["UnitName"].ToString()),
CellText(dtparent.Rows[0]["UnitName"].ToString()),
CellText(dtparent.Rows[0]["ParentUnitId"].ToString()),
CellText(dtparent.Rows[0]["Address"].ToString()),
CellText(dtparent.Rows[0]["City"].ToString()),
CellText(dtparent.Rows[0]["EmailId"].ToString()),
CellText(dtparent.Rows[0]["PhoneNo"].ToString()),
CellText(dtparent.Rows[0]["FaxNo"].ToString()));
Now i have another page called "Add.aspx Page"
in that page i have textbox
<asp:TextBox ID="txtunitname" runat="server" CssClass="textbox"></asp:TextBox>
now i just want on click on dynamically create button on "tree.aspx" page the "unitname(dynamically create value)" will pass "Add.aspx" page and textbox should fill with unitname.
kindly help me,
Thanks.
To pass pass values using asp.net you need to follow the asp.net way.
First on the first page you place that value on a page control, I prefer on your case a hidden field, that is also post back to any page.
Then you add your value to that field
ValueHiddenField.value = CellText(dtparent.Rows[0]["UnitName"].ToString())
and you make also a public field so the second page can read it
public string ValueHiddenField
{
get
{
return ValueHiddenField.value;
}
}
And you say to the button to post back to the second page using the PostBackUrl field of the button.
Now this is the way you get your data from second page:
On the redirect page declare what is the previous page on aspx as:
<%# Reference Page ="~/PreviousPageName.aspx" %>
and on code behind on second page you get the value as:
if (Page.PreviousPage != null)
{
if (Page.PreviousPage is PreviousPageClassName)
{
Label1.Text = ((PreviousPageClassName)Page.PreviousPage).ValueHiddenField;
}
else
{
Label1.Text = "no value";
}
}
else
Label1.Text = "no value from previous page";
Similar answers:
cross page posting
Cross-page posting. Is it a good pratice to use PreviousPage in Asp.net?

Route values could not taking to the values

I want to route from one page to another page.
Candidatesvas- controller
Here I have code,
[Authorize, HttpPost,HandleErrorWithAjaxFilter]
public ActionResult Details(FormCollection collection)
{
Order order = _repository.GetOrder(LoggedInOrder.Id);
order.CreateDate = DateTime.Now;
order.Amount = 360;
order.Validity = 60;
_repository.Save();
}
when I click Index page,"any link", it saves in db and go to next details page.
Index.aspx:
<%:Html.actionlink("Details","Details","Candidatesvas")%>
like that...
Global.ascx:
routes.MapRouteLowercase(
"SaveVas",
"details/candidatesvas",
new { controller = "Candidatesvas", action = "Details" }
);
But when i click link, it shows "resource cannot be found". i changed many way. please help me. i can't find out the issue?
Your controller action is decorated with the [HttPost] attribute which means that this action is only accessible with the POST verb. Then you have shown some link on your page:
<%:Html.ActionLink("Details","Details","Candidatesvas")%>
But as you know a link sends GET request. If you want to be able to invoke this action you should either remove the [HttpPost] attribute from it or use an HTML <form> instead of a link.
try this
<%:Html.actionlink("Details","Details","Candidatesvas",null,null)%>
You can't use Html.actionlink for post method.
go for jquery
Or call form submit on click function.

call code behind functions with html controls

I have a simple function that I want to call in the code behind file name Move
and I was trying to see how this can be done and Im not using asp image button because not trying to use asp server side controls since they tend not to work well with ASP.net MVC..the way it is set up now it will look for a javascript function named Move but I want it to call a function named move in code behind of the same view
<img alt='move' id="Move" src="/Content/img/hPrevious.png" onclick="Move()"/>
protected void Move(){
}
//based on Search criteria update a new table
protected void Search(object sender EventArgs e)
{
for (int i = 0; i < data.Count; i++){
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell CheckCell = new HtmlTableCell();
HtmlTableCell firstCell = new HtmlTableCell();
HtmlTableCell SecondCell = new HtmlTableCell();
CheckBox Check = new CheckBox();
Check.ID = data[i].ID;
CheckCell.Controls.Add(Check);
lbl1.Text = data[i].Date;
lbl2.Text = data[i].Name;
row.Cells.Add(CheckCell);
row.Cells.Add(firstCell);
row.Cells.Add(SecondCell);
Table.Rows.Add(row);
}
}
Scott Guthrie has a very good example on how to do this using routing rules.
This would give you the ability to have the user navigate to a URL in the format /Search/[Query]/[PageNumber] like http://site/Search/Hippopotamus/3 and it would show page 3 of the search results for hippopotamus.
Then in your view just make the next button point to "http://site/Search/Hippopotamus/4", no javascript required.
Of course if you wanted to use javascript you could do something like this:
function Move() {
var href = 'http://blah/Search/Hippopotamus/2';
var slashPos = href.lastIndexOf('/');
var page = parseInt(href.substring(slashPos + 1, href.length));
href = href.substring(0, slashPos + 1);
window.location = href + (++page);
}
But that is much more convoluted than just incrementing the page number parameter in the controller and setting the URL of the next button.
You cannot do postbacks or call anything in a view from JavaScript in an ASP.NET MVC application. Anything you want to call from JavaScript must be an action on a controller. It's hard to say more without having more details about what you're trying to do, but if you want to call some method "Move" in your web application from JavaScript, then "Move" must be an action on a controller.
Based on comments, I'm going to update this answer with a more complete description of how you might implement what I understand as the problem described in the question. However, there's quite a bit of information missing from the question so I'm speculating here. Hopefully, the general idea will get through, even if some of the details do not match TStamper's exact code.
Let's start with a Controller action:
public ActionResult ShowMyPage();
{
return View();
}
Now I know that I want to re-display this page, and do so using an argument passed from a JavaScript function in the page. Since I'll be displaying the same page again, I'll just alter the action to take an argument. String arguments are nullable, so I can continue to do the initial display of the page as I always have, without having to worry about specifying some kind of default value for the argument. Here's the new version:
public ActionResult ShowMyPage(string searchQuery);
{
ViewData["SearchQuery"] = searchQuery;
return View();
}
Now I need to call this page again in JavaScript. So I use the same URL I used to display the page initially, but I append a query string parameter with the table name:
http://example.com/MyControllerName/ShowMyPage?searchQuery=tableName
Finally, in my aspx I can call a code behind function, passing the searchQuery from the view data. Once again, I have strong reservations about using code behind in an MVC application, but this will work.
How to call a code-behind function in aspx:
<% Search(ViewData["searchQuery"]); %>
I've changed the arguments. Since you're not handling an event (with a few exceptions, such as Page_Load, there aren't any in MVC), the Search function doesn't need the signature of an event handler. But I did add the "tablename" argument so that you can pass that from the aspx.
Once more, I'll express my reservations about doing this in code behind. It strikes me that you are trying to use standard ASP.NET techniques inside of the MVC framework, when MVC works differently. I'd strongly suggest going through the MVC tutorials to see examples of more standard ways of doing this sort of thing.