This article shows you how to easily protect against CSRF attacks using MVC.NET’s ValidateAntiForgeryToken and prompt a user with a confirmation popup using jquery UI when submitting a form to multiple controller actions. Code examples are included for jquery.UI version 1.8.9 with the redmond theme and ASP.NET MVC 3 in a form with two secure submit input buttons to get a neat confirmation dialog:

Here’s the code for the confirmation dialog box and button click event for the other submit button. You want this to be inside the asp:Content tags but outside the Html.BeginForm (form) tags:

<%-- confirmation div must exist outside the form but inside the Content --%>
<div id="confirmation" title="Confirmation"> 
<p>You are about to submit this to the OtherControllerAction.</p>
<p>If this is correct, press Continue.</p>
</div>
<script type="text/javascript">   
    $('#confirmation').dialog({  
        autoOpen: false,  width: 400,  modal: true,  resizable: false,  
        buttons: {   
            "Continue": function() {    
                <%-- change the controller action where the form submits for the other submit button --%>    
                $('form').attr({
                    action: "<%:Url.Action("OtherControllerAction")%>/<%: Model.MyId %>"});    
                    $('form').submit();   
                },   
            "Cancel": function() {    
                $(this).dialog("close");   
                }  
            } 
    });
</script>

This is the code for the submit button that uses the Html.Submit default post location, and the other submit button that is wired to the other controller action in the above code:

<%: Html.AntiForgeryToken() %>
<input type="submit" value="Submit to Default Controller Action" />
<button type="button" onclick="$('#confirmation').dialog('open')"> Submit to Other Controller Action</button>

Both controller actions can be easily protected against CSRF attacks with the ValidateAntiForgeryToken decorator:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyDefaultControllerAction(MyVM viewModel)
{
    ...
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult OtherControllerAction(string id)
{
    ...
}

« »