Stimmler
Stimmler

Reputation: 462

How to implement an ASP.NET Core controller supporting Razor and Angular?

Currently, I'm writing a web application in C# ASP.NET Core and Razor Pages.

In the future I want to replace my frontend with an Angular application. Now I'm wondering how to set up my controllers to serve both technologies.

The problem is, that my controller methods have to return a ViewResult object to properly render the view when using Razor Pages. The result obviously can't be used in Angular and the controller methods aren't really RESTful which I want them to be.

So is there a way to implement a controller supporting Razor and Angular?

Thanks in advance

Upvotes: 2

Views: 450

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26352

If you are going the angular way, not really. Angular expects communication using Xhr requests.

There is even a template in net core for angular applications: https://learn.microsoft.com/en-us/aspnet/core/client-side/spa/angular?view=aspnetcore-3.1&tabs=visual-studio

In theory you could achieve what you want with some duplication.

I.e.:

[HttpGet]
public ActionResult Index()
{
     IndexViewModel viewModel = GetIndexModel();
     // Add action logic here
     return View(viewModel);
}

[HttpGet]
public IndexViewModel GetIndexModel() {
   // return the view model.
}

The second get function can be used as xhr request from your angular application. This is not really recommended. Going angular is a good opportunity to turn your api to Rest and properly handle the data in your spa.

Upvotes: 1

Related Questions