locked
Razor Pages - Page Model Class (.cshtml.cs) without Razor Page (.csthml )? RRS feed

  • Question

  • User2104731553 posted

    I have a situation where I (assume) that I need a page model class without the actual cs.html razor page, but I don't know if this is a best practice or not, so I am open to suggestions.

    I am developing a social media platform similar to Facebook in functionality. I have "add friend" and "remove friend" buttons scattered across the application. I need to implement these post actions, and they will be called via AJAX. However, I really do not need the corresponding razor (.cshtml) pages to go with these post methods. This is similar to Facebook, because when you add a friend, rather than taking you to an "add friend" crud page, the site simply uses AJAX to call the respective post action.  

    So my question is, what is the proper convention for storing post actions in a situation like this? Do I make a page model class without the corresponding razor page, and have it redirect back to the page that called it, after it performs it's post action? If not, how should this be done?

    Wednesday, February 12, 2020 4:48 AM

Answers

  • User-821857111 posted

    What you are basically describing is a series of API endpoints - HTTP services that return data (even if it's just a flag to indicate the result of the POST operation), not views. It is certainly possible to add PageModel classes to your application and use named handlers etc to return JsonResults, but the recommended way to do this is to add API controllers instead: https://www.learnrazorpages.com/web-api

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 12, 2020 7:46 AM

All replies

  • User-821857111 posted

    What you are basically describing is a series of API endpoints - HTTP services that return data (even if it's just a flag to indicate the result of the POST operation), not views. It is certainly possible to add PageModel classes to your application and use named handlers etc to return JsonResults, but the recommended way to do this is to add API controllers instead: https://www.learnrazorpages.com/web-api

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 12, 2020 7:46 AM
  • User2104731553 posted

    Thank you, I will look into this.

    Wednesday, February 12, 2020 4:18 PM
  • User-821857111 posted

    I should have clarified -  a PageModel also needs its .cshtml file otherwise its handlers won't be routeable.

    Wednesday, February 12, 2020 7:36 PM