title: ASP.NET Core 2, button click with Razor pages without MVC
body: <p>As someone pointed out in a comment, Razor pages doesn't need Controllers, like you're used to do in MVC. I also now Razor doesn't have a native handling of the button click event. To do something (in the "code-behind") when the user click a button we have at least two options:</p>
  
  <ul>
  <li>use a submit button</li>
  <li>use an ajax call</li>
  </ul>
  
  <p>I find a LOT of examples for MVC that show how to define the Controller functions. But as said, I don't have one.</p>
  
  <p>Hence I'm trying to understand both ways. Here my test cshtml:</p>
  
  <pre><code>&lt;form method="post"&gt;
      &lt;input type="submit" class="btn btn-primary" value="way1"&gt;Way 1/&gt;
  &lt;/form&gt;
  
  &lt;button id="btn" type="button" class="btn btn-primary" value="way2"&gt;Way 2&lt;/button&gt;
  
  &lt;script&gt;
  $(document).ready(function() {
      $("#btn").click(function (e) {
          e.preventDefault();
          $.ajax({
              url: "@Url.Action("Way2")",
              type: "POST",
              data: "foo",
              datatype: "text",
              success: function (data) {
                  alert(data);
              }
          });
          return false;
      });
  });
  &lt;/script&gt;
  </code></pre>
  
  <p>and here the cshtml.cs:</p>
  
  <p>public class TestModel : PageModel
  {
      private readonly MyContext _context;</p>
  
  <pre><code>public TestModel(MyContext context)
  {
      _context = context;
  }
  
  public IActionResult OnPost()
  {
      // here I can put something to execute 
      // when the submit button is clicked
  }
  
  public ActionResult Way2(string data)
  {
      // this is never triggered
  }
  </code></pre>
  
  <h2>Questions</h2>
  
  <ol>
  <li><p>With the "Way1" (submit) I'm able to catch the click of a button, but with some drawbacks. By default the page is reloaded due to the post. Sometimes I don't need to change anything, but just call a C# function. But I don't understand how to handle multiple buttons. I.e. if I have 5 buttons, how to do something different for each one?</p></li>
  <li><p>With the "Way2" I did something wrong because the function in cs code is never reached and I get a Bad Request error (400). What did I miss?</p></li>
  </ol>