I am trying to handle multiple form submissions by writing an ActionFilter. I am new to the domain of ActionFilters and dont know where to start any help will be much appreciated. I have looked at this question but couldnt get a starting point
Asked
Active
Viewed 644 times
3 Answers
3
I would use antiforgery token for this. You should have it generated already (if you dont want to be vulnerable to CSRF attacks), and it is unique for every generated form.. so you can create an filter which will do basically this :
- look in form collection for antiforgery token
- look into session["LastFormToken"] (or whatever key you like) - if this form (token) already been submitted
- if yes, drop the request, if no (form is submitted first time), put it in session (so next time it will be found there and request will be dropped)

rouen
- 5,003
- 2
- 25
- 48
0
I would like to suggest an answer. Here is the code
public class ValidateSubmitOnceTokenAttribute : ActionFilterAttribute
{
public String ErrorView { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
String submitOnceToken = null;
submitOnceToken = filterContext.HttpContext.Request[ViewHelper.SubmitOnceIdentifier];
if ((bool)filterContext.HttpContext.Session[ViewHelper.SubmitOnceIdentifier + submitOnceToken])
{
if (String.IsNullOrEmpty(View))
{
filterContext.Result = new EmptyResult();
}
else
{
ViewResult newView = new ViewResult();
newView.ViewName = ErrorView;
filterContext.Result = newView;
}
}
else
{
filterContext.HttpContext.Session[ViewHelper.SubmitOnceIdentifier + submitOnceToken] = true;
}
}
}
public partial class ViewHelper
{
internal const string SubmitOnceIdentifier = "_SUBMIT_ONCE_";
public static MvcHtmlString SubmitOnceToken()
{
Guid submitOnceToken = Guid.NewGuid();
HttpContext.Current.Session[SubmitOnceIdentifier + submitOnceToken] = false;
return new MvcHtmlString("<input type=\"hidden\" name=\"" + SubmitOnceIdentifier + "\" value=\"" + submitOnceToken.ToString() + "\">");
}
}
After that, you just need to include this attribute in your method
[ValidateSubmitOnceToken(View="ErrorSubmitOnce")]
public ActionResult MyAction(Model) {
....
}
And include this in your view
@ViewHelper.SubmitOnceOnlyToken()
This answer uses the technique described by Aliostad but implemented using an action filter.

Terrence Tan
- 532
- 5
- 10
0
http://blogs.sonatribe.com/wayne/2011/08/15/acceptparameterattribute-update/
I explain how to create an attribute that allows you to switch the target action based on the name of the submit button initiating the submit.
Let me know if you need pointers
-
tnx for answering but thats not what i need i have a single form with a single submit button but some times due to slow server response the user clicks the button several times and the form is submitted multiple times – John x Nov 24 '11 at 11:51