can I return object in razor pages?

mc 5,426 Reputation points
2025-01-18T02:34:55.8966667+00:00

can I return object in razor pages?

public async Task<object>OnPostDeleteAsync()
{
return MySuccessMessage();
}
Developer technologies | ASP.NET | ASP.NET Core
{count} votes

Accepted answer
  1. Anonymous
    2025-01-20T06:14:02.8566667+00:00

    Hi @mc,

    You can return an object in Razor Pages, but it may not work as what you done. Razor Pages are designed to return IActionResult objects for HTTP responses. If you return a plain object, it won't automatically serialize to JSON or render properly.

    To properly handle this, you should return a JsonResult to send JSON data, especially for AJAX requests.

    For Example, modify your code like below:

    public async Task<IActionResult> OnPostDeleteAsync()
    {
        return new JsonResult(new MySuccessMessage());
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2025-01-18T12:13:25.99+00:00

    can I return object in razor pages?

    I'm guessing you have a client application, maybe JavaScript, that calls OnPostDeleteAsync(). The problem you are trying to solve, is making an AJAX call to delete a resource. But, you need the results of the delete operation to update the document loaded in the browser. See the following tutorial if you are trying make AJAX calls to Razor Page handlers and process the results.

    https://www.mikesdotnetting.com/article/318/working-with-json-in-razor-pages

    If the above does not answer your question, then explain what you are trying to do.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.