stefan.stt
stefan.stt

Reputation: 2627

Calling controllers method from page with asp-action

Whatever I do the button bellow always calls the OnGetAsync() method of the controller, not the desired SetEditMode()

Controller/Model code:

public class DetailsModel : PageModelBase
{
    private readonly ICommunicationService communicationService;

    public DetailsModel(ICommunicationService communicationService)
    {
        this.communicationService = communicationService;
    }

    public bool IsEditMode { get; set; } = false;

    public EmployeeProfileData EmployeeProfileData { get; set; }

    public async Task OnGetAsync()
    {
        this.EmployeeProfileData = await this.communicationService.GetEmployeeProfileData();
    }

    [HttpGet(nameof(SetEditMode))]
    public IActionResult SetEditMode()
    {
        this.IsEditMode = true;
        return Page();
    }
}

View code:

@page
@using Common.Resources
@model PersonalProfile.DetailsModel
@{
    ViewData["Title"] = TextResources.Profile;
}

<div class="row no-padding col-md-12">
    <h3 class="pl-3 mb-3 text-color-medium float-left">@TextResources.EmployeeProfileData</h3>
    @if (!Model.IsEditMode)
    {
        <div class="d-flex justify-content-start mb-2 mx-2">
            <a asp-action="SetEditMode" method="get" class="btn btn-light-green">Edit</a>
        </div>
    }
</div>

Upvotes: 1

Views: 839

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93293

You are working with a Razor Page, rather than a Controller. In your example, you're confusing Razor Pages routing with the attribute-based routing approach used with Controllers.

For this to work, you can use a Named Handler Method, which follows a convention of On[Verb][Handler]. Here's an example:

public IActionResult OnGetSetEditMode()
{
    this.IsEditMode = true;
    return Page();
}

Note that I've also removed the HttpGet attribute above.

With this change, the .cshtml file needs to be updated to use the new handler:

<a asp-page-handler="SetEditMode" class="btn btn-light-green">Edit</a>

Note that I've also removed the method attribute in this case, as a elements trigger GET requests by design.

Upvotes: 2

Related Questions