Home > Back-end >  Same OnPost handler with different parameters
Same OnPost handler with different parameters

Time:06-15

I have a for with the following submit actions:

<form  method="post">
    <input type="submit" value="Test1" asp-page-handler="Button1"/>
    <input type="submit" value="Test2"  asp-page-handler="Button2"/>
</form>

with .cs file:

public IActionResult OnPostButton1(IFormCollection data)
    {
        if (ModelState.IsValid == false)
        {
            return Page();
        }

        await _db.InsertOrUpdateComments(param1);

       return Redirect("/Projects/Index");
    }

   
    public IActionResult OnPostButton2(IFormCollection data)
    {
        if (ModelState.IsValid == false)
        {
            return Page();
        }

        await _db.InsertOrUpdateComments(param2);

       return Redirect("/Projects/Index");
    }

This works well for what I want, however I wanted to know if I can combine it, as you see, there is pretty much no difference on the post methods other than the parameter passed, I wanted to know if I can combine these submit into a single one and have a condition to know which parameter to pass.

such as if user clicks on Button1 will call the same OnPost as Button2 but passing a different parameter that will be used for "param1" or "param2".

CodePudding user response:

To take advantage of Razor Pages model binding (rather than delving into the FormCollection manually), you can add a bound property to your PageModel class:

[BindProperty]
public string Action { get; set; }

Then add a name attribute to the submit buttons, which now both have the same handler name, so that the value of the button is bound to the PageModel property:

<form  method="post">
    <input type="submit" name="Action" value="Test1" asp-page-handler="Button"/>
    <input type="submit" name="Action" value="Test2"  asp-page-handler="Button"/>
</form>

Then in your single handler, you can test the value of the Action property:

public IActionResult OnPostButton()
{
    if (ModelState.IsValid == false)
    {
        return Page();
    }
    var p  = Action == "Test1" ? p1 : p2;
    await _db.InsertOrUpdateComments(p);

    return Redirect("/Projects/Index");
}
  • Related