1

As I was exploring the articles and contents on the internet about building REST APIs using asp.net core, I found out that razor web pages are not commonly used for front-end. Most of them are focused on Angular 1 && 2 for dealing with api data coming from the server (Ex: $http.get, $http.post). I was just wondering if there is any article that introduces how to use pure razor web pages as a front-end for dealing with web api or is there any ways to do it properly using .net core?

For ex:

[Route("api/students")]  
public class StudentsController : Controller
{
    private IStudentRepository _repository;

    public StudentsController(IStudentRepository repository)
    {
        _repository = repository;
    }

    [HttpGet("")]
    public IActionResult Get() 
    {           
        var results = _repository.GetAllStudents();

        return Ok(Mapper.Map<IEnumerable<StudentViewModel>>(results));
    }

And instead of using angular's $http service to render in view,

$http.get("/api/students")
    .then(function (response) {          
        ...
    }

is there any method to render api in razor view?

bbusdriver
  • 1,577
  • 3
  • 26
  • 58
  • 1
    That's not what Razor is for. It is a rendering engine for HTML that executes on the server. It will not do the javascript code to call APIs. You will ultimately need to write the code to do that. You can still use Razor to create your HTML pages, but I think you will be better off if you write that portion in something other than Razor. – MichaelDotKnox Dec 19 '16 at 03:00
  • Thanks for your comment. Does that mean that I should write in some other languages such as jQuery for integrating web api in razor web pages? (If I am not going to use angular, etc) Is [this](http://www.mikesdotnetting.com/article/261/integrating-web-api-with-asp-net-razor-web-pages) approach still relevant in .net core? – bbusdriver Dec 19 '16 at 05:11

1 Answers1

2

You can use razor to call WebAPI but it's fairly pointless as you would miss out on all of the benefits of modern web development, eg you would have to postback to the server and reload the entire page instead of having an ajax request and just loading part of the page.

Essentially you would have to call your webapi from your MVC controller or some facade class within the controller, get the data response and then output that in a view using razor.

I'm not going to even bother posting code for this as you would be better off using Angular or some JS framework as you will end up with a better product.

matt_lethargic
  • 2,706
  • 1
  • 18
  • 33