Reset input fields after submission - asp.net

I'm working on an asp.net core project. I have some issues with the reset button. when I enter data which is already saved. The error message is shown as I given. After this reset button is not working.

I suggest after the submit, to either reset them with javascript, either if you use a post back, redirect to the same page (without post back this time).
For example this core redirects to him self, and the form is clear now.
Response.Redirect(HttpContext.Current.Request.RawUrl);
Or you can use this javascript code together and avoid the post back
OnClientClick="return (confirm('Clear Form ?') && this.form.reset(),false)"

Your question is very unclear, but it sounds like what you're talking about is actually the client-side validation. Once validation has been activated (by entering something into a field), validation will remain active. If you then clear that field (using the reset button, for example) and it's required, you'll still have a message saying the field is required, because it is, and it's now empty. If you want to clear all these validation messages, as well, then you need to do something like:
$('[type=reset]').on('click', function () {
let validator = $(this).closest('form').validate();
validator.resetForm();
});

Related

How can I avoid a postback message?

I am relatively new in programming and I have a doubt about postback. I searched in some pages, but I couldn't solve my question.
I created a web page and I use postback in it that updates some informations in the page. That works without any problems. However, after the postback is fired, if the user presses F5, a message appears asking to confirm the form re-submit.
Why exactly this message appears and how can I avoid it?
If the user would press F5, I want the page reload, without any alerts.
I'm sorry if my question wasn't clear enough, but I really don't understand postback how much I'd like.. =)
By Default ,
The method is post means it will confirm while reloading the page.
The method is get means it wont ask anything.
Why this happens,Whenever the post method called severe action gonna happen in server,so it just confirms from the user.There is no need in the case of get Method.
I hope u are clear with this solution.
One way to avoid your issue is to place a hidden field on the page. When the form is submitted, check the hidden field. If no value, process the form, and populate the hidden field with a value. If it has a value, then do nothing.
I prefer using an on-click event on a button, instead of using the postback event.
As to why it happens, a refresh sends a request along with the form data back to the server causing another postback.
This is known as page re-submission.
When you refresh the browser, it will resend the last request you did. If it was a POST request (like you do in case of postback) then it will re-post the information but before doing it you'll see the warning message you describe.
To prevent this:
Page.Response.Redirect(Page.Request.Url.ToString(), true);
Which changes the response to a GET instead of a POST. Prevents the 'Form Resubmission' dialog.
I thought in the following code to solve my problem, using a javascript event:
$(document).keydown(function (event) {
if (event.keyCode == 116) {
location.href = 'pedidos.aspx';
return false;
}
});
It solves my problem, because I avoid the postback message as I want and the page is reloaded.
But is this a good solution?

Submit form to both code behind and third party url?

I have a legacy app that I need to change to accommodate a new payment processor.
The app is Asp.Net.
Without reconstructing the app (not in the budget) I need to take the final form and save information from it in the code behind, like it currently does, then I need to submit that same form to a third party url. Ideally as one button push to the end user.
I'm drawing a complete blank on a way to do this. Any suggestions?
Forgot to mention that JQuery and javascript are both valid tools for a solution.
You could create a javascript function that's bound to the form submit button's click event, or the form's submit event. The function will need to prevent the default form submission from firing. Use jQuery to serialize the form data, and create a synchronous AJAX request to submit the data to the third party. After the ajax submission has completed, you can trigger the form submission to the code-behind. If the ajax fails to submit properly, you can optionally abort the form submission to the code-behind.
You may need to account for XSS security, so look into cross-origin resource sharing and the Access-Control-Allow-Origin header.
Another option would be to have the code-behind behave as an http client and submit the form data to the third party.
so currently it's saving the results via code? Well, you could hack it by putting some javascript on the page that read's the forms values and posts them (eg with jquery), before doing you actual asp post.
edit (something like this might help (in some cases):
//change the action of the form (you could just change in code or this
$('#myform').attr('action','http://newpaymentproc.com/me/');
//override the default submit
$('#myformsubmitbutton').click(function(){
//extract the form data somehow (depends on form)
var formObj;
$.each($('#myform').find('input').serializeArray(), function(i, field) {
formObj[field.name] = field.value;
});
//post to old place
$.post('/old_current.asp', formObj).then(
//after posting to old place and getting response...
//submit form to new payment processor
$('#myform').submit()
);
// Cancel the actual form submit click to give time for post
return false;
});
Another way would be to have the legacy code (after submission) spit out a form with the data in it and some javascript to trigger submit on page load.
After the original process has completed, just take the submitted form data and push it to whichever URL you're working with. It requires minimal modification on the original app.
I have no code to go on, so I have no code to give. Hope that helps!

Ajax comments form in ASP.NET MVC2, howto?

I've been playing around with different aspects of MVC for some time now, and I've reached a situation where I'm not sure what would be the best way to solve a problem. I'm hoping that the SO community will help me out here :P
I've seen a number of examples of Ajax.BeginForm on the internet, and it seems like a very nifty idea. E.g. you have a dropdown where you select a customer - and on selecting one it will load this client's details in some placeholder on the page. This works perfectly fine.
But what to do if you want to tie in some validation in the box?
Just hypothetically, imagine an article page, and user comments in the bottom. Below the comments area there's an ajax-y "Add comment" box. When a user adds a comment, it will appear in the comments area, below the last comment there.
If I set the Ajax.BeginForm to Append the result of the call to the Comments area, it will work fine. But what if the data posted is not valid? Instead of appending a "successful" comment to the comments area I have to show the user validation errors.
At this point I decided that the area INSIDE the Ajax.BeginForm will be inside a partial, and the form's submits will return this partial. Validation works fine. On each submit we reload the contents inside the form element. But how to add the successful comment to the top?
Other things to consider: The comment form also has a "Preview" button. When the user clicks on Preview, I should load the rendered comment into a preview box. This will probably be inside the form area as well.
I was thinking of using Json results instead. When the user submits the form, the server code will generate a Json object with a Success value, and html rendered partials as some properties. Something like
{ "success": true, "form": "<html form data>", "comment": "successful comment html to inject into the page" }
This would be a perfect solution, except there's no way in MVC to render a partial into a string, inside the controller (separation of context, remember?).
UPD: Seems like nobody knows an answer to this one.. Does it mean that there's no way to do this, or you just don't know, guys?
Here is an example how to post using jQuery and how to deal with error in the validation.
http://jvance.com/blog/2010/02/20/MakingAnAjaxFormWithJQueryInASPdotNETMVC.xhtml
After giving it more consideration + getting more experience with MVC, I decided to break down the problem, and came to the following conclusion. Not sure if anyone will find it useful
With an Ajax.BeginForm that requires field validation, the return from the submit should return the form's html. This way, if the validation failed- the response will contain the error messages, and the interface will look seamless.
The result will also most likely contain the whole form, including the declaration of it.
The preview in this case is a simple issue. When the user clicks on the preview button, the form can be posted, and the result will contain the populated form + the preview box. Alternatively, the Preview button can be an Ajax.LinkButton that will serialize the form, post the data to the server, that will render it into a comment. The js on the client side will then put this preview in the required container.
On successful submit, there are a couple options, depending on the requirements and the layout.
a) The result of the form submit can return the comment + the blank form (ready for a new comment)
e.g. when the comment form is below all the comments, this will look as if the comment has been added to the bottom of the form
b) The result can contain the blank form + a small js script that will update the comments area / load the latest comment to the page
c) It can also force a refresh of the parent page, to ensure the newly posted comment will be immediately visible to the user.
Basically, this choice depends on the requirements of the particular case.

Is javascript reliable for preventing actions on the front end such as form submission?

I have a webservice that I need called, the result of which determines whether or not the user is allowed to submit the form.
Since this call is from javascript and not from code behind is it not reliable? Is there any way the user can get around the check -- by either going in with firebug and enabling the submit button, somehow making the method give a different result than was actually returned by the webservice, any other ways of being able to get around it?
Basically is there any way to call a webservice from javascript and have it's result determine whether or not a form can be submitted, and actually prevent the user from submitting the form at all? -- whether or not they have firebug, etc...
No, not possible.
Just to name a few possible reasons:
what if javascript is disabled?
what if the user submits the raw POST (using libcurl, for example)?
what if the browser, that the user is using interprets javascript in a way, different from your expectations (think, portable devices)?
Javascript validation is there for your users' convenience only and should never ever be used as a means of providing security.
You can never prevent the user from making an HTTP request that mimics submission of the form. While disabling the form via Javascript prevents submission for 95% of the users who both have Javascript enabled and don't want to circumvent your access control, anyone who understands HTTP can make the call and you are correct in showing that anyone with Firebug can do it in a matter of seconds.
Javascript isn't reliable for preventing anything. It shouldn't be seen as a security-wall, as it's too easily disassembled with things like firebug, iedevelopertoolbar, and many other browser toys.
Even if you could prevent them from submitting your form on your page, nothing stops them from creating a brand new form, on their own page, and point it toward the action of your form. Thus they're removing themselves from your "secure" environment, and instead chosing to play in their own.
Your suspicion is correct; the user can easily get around any possible Javascript validation.
You will need to use server-side code.
No, it is not reliable. Try disabling Javascript in your browser to see for yourself how easily you can get around it.
The user could simply disable javascript in their browser, or use something like NoScript. The best you could do is to try setting the form action itself in the return from the Ajax request, that way the form, as loaded, won't submit (except to itself). This will probably stop casual users but would be no impediment to a slightly more determined (or just bored and tech savvy) user. You will need to check on the server side whatever you do.
In general, no. You can make the form hard to submit without going through Javascript. Make the submit button not an actual submit button (<input type="submit">), but a pushbutton (<input type="button">) that submits the form in its onClick handler.
As everyone else said, no you can't do it. The only real solution is to have the web service return some dynamic value which the Javascript inserts in a hidden form input. Then whatever server-side code processes the form submission should reject the request if that value is not present.

How do I remove a page from the browser history?

I have an have an ASP.Net page which contains a button. This Page contains a ServerSide Paypal button.
When pushed my server does various clever things on the back end and then rewrites the response as a form and some javascript which posts this form to paypal..
This all works great.
However, if the user then elects to click back, they will arrive at my generated self-posting form and that will forward them again to Paypal.
I thought if I could find a way to have my generated form page not exist in the history, then this will solve my problem. but I have no idea how to correct this.
How can I remove my page from the history or just have it never appear?
Update: Thanks to all... Those are some great answers. Upvoted all good ones but went with splattne on account of clever use of hidden field rather than cookies for basis of decision.
window.location.replace(URL);
window.location:
replace(url)
Replace the current document with the
one at the provided URL. The
difference from the assign() method is
that after using replace() the current
page will not be saved in session
history, meaning the user won't be
able to use the Back button to
navigate to it.
I'm not sure if that can be done. But here is an idea how you could prevent that resubmit of the form.
You could insert a hidden input in your form which at the beginning would be empty. On submit you'll write a value in that field and make sure you check on every submit attempt if this field is empty.
If it is not empty on submit you know that the form was previously sent and you could warn the user.
As a web application, you'll never have full control of the user's browser. Even if there was a way to instruct the browser to not store the page in history, which I doubt, you can't be sure it'll work. For example, a clever user could tweak an open-source browser to store every page in history, no matter what.
I think you should try to approach the problem from another angle. You could, for example, detect that it's the same form which is being forwarded and not send it to paypal the second time. The important thing is to do it server-side.
Perhaps you could set a cookie before submitting the form.
When the page is loaded, check for the existence of that cookie (meaning the form was already submitted). If found, instead of automatically submitting the form, automatically go back (window.history.back()) again.
I'm not sure if you can do this easily with PayPal integration, but the
"Post / Redirect / Get" pattern can be used to address this problem
A useful Hint for some might be this...
window.history.go(-2);
particularly in the advent of a load failure warning popup.
You could simply programme your page not to submit, or to do something / navigate somewhere else, if window.referer is the Paypal page you are trying to avoid invoking a second time.
protected void Page_Load(object sender, EventArgs e)
{
Page.RegisterClientScriptBlock("", "<script>if(history.length>0)history.go(+1);</script>");
}

Resources