Home > OS >  NET 6 Core using Pages posting to a custom method
NET 6 Core using Pages posting to a custom method

Time:03-03

Using the NET 6 core application with Pages.

Right out of the box the project has the following "code behind"

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public void OnGet()
    {

    }

    // This is this the new code 
    public void MyCustomMethod()
    {
        var debug = "Stop Here debug break point";
    }
}

The front end has the following:

@page
@model IndexModel
@{
   ViewData["Title"] = "Home page";
}

<div >
   <form action="MyCustomMethod" method="get">
       <input type="submit" />
   </form>
</div>

Unable to GET or POST to the custom method (MyCustomMethod) in the NET 6 CORE using PAGES.

It could be a dumb question by I tried to google for the past 2 hours and can not find anything related to what I am doing. Please help.

Trying to use a simple form to get or post to the "code behind". When page load I do see a debug going into OnGet() method which it should do but clicking on a button in a form it never makes it into MyCustomMethod().

Thank you.

Did the following change to a code:

    [HttpPost] // Second run added this because it was still not working
    public void OnPostMyCustomMethod()
    {
        var debug = "Stop Here debug break point";
    }

Front page
    <form action="MyCustomMethod" method="post">
    <input type="submit" />
</form>

Still unable access:

Debug Run

CodePudding user response:

Razor Pages includes a feature called "named handler methods". This feature enables you to specify multiple methods that can be executed for a single verb.

If you have set the OnPostMyCustomMethod or MyCustomMethod in the backend codes, you should use this url "https://localhost:7086/?handler=MyCustomMethod" to access it.

More details, you could refer to below example:

  <form asp-page-handler="MyCustomMethod"   method="post">
       <input type="submit" />
   </form>
  • Related