C# MVC Detect which button was clicked

Detecting which button was clicked to cause a post back is very easy, once you know how to do it!

I often have screens that have multiple submit buttons on a single form that require a post back. I needed to pass the button value to the controller in MVC. For instance, I may have a data entry screen where a user can click a button that says “Save” or “Save as New”. I need to be able to detect which button they clicked when the page posts back.

Fortunately, there is an easy way to tell, or determine, which button the user selected when the page posts back on a submit action.

First, you need to have a button setup like so:

<form id="rvWidgetForm" method="post" enctype="application/x-www-form-urlencoded" asp-controller="Search" asp-action="SearchBegin">

    <button id="btnTopTen" type="submit" name="submitButton" class="btn text-center" value="TopTen">
        TOP 10 SEARCH
    </button>

    <button id="btnTraditional" type="submit" name="submitButton" class="btn  text-center" value="Trad">
        TRADITIONAL SEARCH
    </button>

</form>

The buttons must be of type=submit. Having type=button won’t post back. You have a choice here, to use the value= or not use it. If you don’t declare a value attribute, then what you’ll receive in the controller is the text of the button. While this is okay, you or another developer may change the text in the future and not realize they are going to break your code. I recommend using the value= like I’ve used above. It’s less likely to change in the future.

I recommend using the value attribute as it’s less likely than the button text to change in the future.

The next most important part is the name attribute. Every button that will post back should have the same name. This will be the name of your parameter in your controller as well and they must match. The value you declare on the button will be the argument passed to your controller method.

public async Task<ActionResult> SearchBegin([FromForm] SearchPageModel _searchModelIn, [FromForm] string submitButton)
    {
        // If you "name" your buttons as "submitButton"
        // then you can grab the value of the button
        // here to make decisions on which button was clicked
        switch (submitButton)
        {
            case "TopTen":
                return TopTen(_searchModelIn);
            case "Trad":
                return Traditional(_searchModelIn);
            default:
                break;
        }

        return View("~/");  // Go home

 }

The parameter name in your method must match the name attribute on your buttons exactly. The type passed in will be a string, although I imagine if your value attribute on all your buttons was numeric, that you could declare it as an int.

Once you’re in your method, you can use logic in a switch statement to detect the value passed in and make a decision how to proceed.

Google reCAPTCHA in HTML and JavaScript

This post is using two HTML pages that have only JavaScript enabled. Feel free to replace some of the code with JQuery if you are loading those scripts. Otherwise, you can implement Google reCAPTCHA in HTML and JavaScript.

Google reCAPTCHA
Google reCAPTCHA

Google has a client side implementation for their reCAPTCHA on your web pages. Their documentation is great at explaining what it is, but it lacks in specific examples for how to implement in different environments. This causes confusion with some developers when they paste the two lines of code in their web page, but they are still able to submit the page, even when they don’t fill in the CAPTCHA.

I’ve noticed during testing that it may be possible to get through the CAPTCHA the first time. On subsequent requests, probably based on IP address, it creates a popup that you have to select photos from. That should stop most bot engines. Just mentioning so you don’t think there’s a problem if you still occasionally get a form submit that looks like it could be a bot.

The getting started section of the Google Developer’s Guide is fine for getting started, but I’ll still cover it here, as I strongly dislike blog posts that only show 80% of the solution.

First thing you need is the actual URL that your going to deploy the application on. So if you haven’t registered one yet, you should do that now. I don’t know how Google handles it when two people try to register the same domain with reCAPTCHA, but I would assume that it would be questioned at some level. Maybe I’ll do an investigation in the future when I’m bored. I just feel that I don’t want to setup a domain under my Google account and then find out later someone else registered the domain and I’ve made a potential problem for them.

Okay, so let’s get started:

  1. Register your domain, as previously mentioned.
  2. Sign up for your reCAPTCHA at Google.
    1. Save your site and private/secret key somewhere in your source control
  3. Place the script call on your page, preferably in the header, but it doesn’t have to be if you use frames etc.
<script src="https://www.google.com/recaptcha/api.js" async defer> </script>

4. WITHIN THE FORM TAGS of your page, place the widget. This is the “Implicit” method of displaying the reCAPTCHA widget.

<div class="g-recaptcha"></div>

5. Create a javascript function that you can call to validate the CAPTCHA response from Google.

function VerifyCAPTCHA() {
	var response = grecaptcha.getResponse();

    alert(response);

    if(response.length == 0)
    {
        // reCaptcha not verified
        var textbox = document.getElementById('errortext');
        textbox.value = 'reCAPTCHA failed you BOT!';
        return false;
    }
    else
    {
		window.location.assign('http://www.yourdomain.com/MyResultsPage.html');
    }
};
6. Create the button that will validate your CAPTCHA on submit.
        <div>
            <input type="button" name="submitButton" value="Show Results!" onclick="javascript: VerifyCAPTCHA();" />
        </div>

A few things to note:
1) Notice that the button is of type “button”, not “submit”. This is because we’re going to depend on our VerifyCAPTCHA() function to redirect us on success.
2) You don’t need your Private/Secret key for this type of implementation.

Now when you run your page with the CAPTCHA on it, it will have to pass this response test before redirecting. On the page you’re redirecting to, you should have some code to verify that the referrer is your CAPTCHA page. This is because any BOT can look for window.location statements and follow them on their own, so you’ll want to stop deep linking in it’s tracks.

The version 1.0 of reCAPTCHA used to allow you to debug using localhost without issue. The new version doesn’t. I can only assume that this was done for security reasons.

I hope that this post helps you to get up and running quickly with Google’s reCAPTCHA without the two or three hours of frustration that I had.