0
votes

Is there any type of way to change the asp .net core 2.x form action in a razor page dynamically in javascript on the page?

Here is my scenario:

  • Two buttons on the page. Call them btn1 & btn2.
  • The code for btn1 needs to always be called.
  • The code for btn2 needs to only be called if btn2.

My assumption would be that I should either:

  • Set a variable that get's checked and see if the btn2 code needs to be called in the OnPost method.
  • I would think that I should do a little bit of refactoring to take my code out of the OnPost method and then put some javascript in to set the form properties appropriately.

Any thoughts on which is the better method to implement?

TIA for your suggestions, Wally

1

1 Answers

1
votes

The simplest approach is to just name your button:

<button name="btn2" type="submit">Click Me</button>

Then, after post, the key "btn2" will only be in the request if the user actually clicked that button. As a result, you can branch on that:

// do some stuff

if (Request.Form.ContainsKey("btn2"))
{
    // do some other stuff
}