0

I am working on a project in VS 2013 using ASP.NET MVC. In one of my cshtml files, I have the following code to return a value (here, and integer):

$.ajax({
        url: '/myproject/api/Test',
        type: 'GET',
        success: function (data) {
            UseResults(data);
        },
        error: function (msg) {
            alert(msg);
        }
    });

The file this routes to, TestController.cs, has this code:

namespace MyProject.Controllers
{
    public class TestController : ApiController
    {
        public int Get()
        {
            return GetThisValue();
        }

        public int GetThisValue()
        {
            //Do work to find and return value...
        }
    }
}

This code currently works properly. It does so by having the ajax call route to the Get() function, which returns the correct value from the GetThisValue() function. However, it is tedious to need the separate Get() function when all it does is call another function. Also, in this program, there will be many different functions using the "GET" method in Ajax, and while it would be possible to route them all through Get(), it would be a lot less cluttered for us to be able to call GetThisValue() directly in the ajax call instead of through Get(). My question is, is there any way to use ajax to route directly to a function that uses [HttpGet] instead of needing it to route first to Get() and then to the other function from there? (Sorry if I didn't put this into words great, if clarification is needed on anything please ask)

thnkwthprtls
  • 3,287
  • 11
  • 42
  • 63

1 Answers1

2

It's easy with attribute routing...

[Route("/myproject/api/test")]
[Route("/some/other/route")]
[Route("/yet/another/route")]
public int GetThisValue()
{
    //Do work to find and return value...
}

You can set up all the separate routes you want to point to that same method.

David
  • 208,112
  • 36
  • 198
  • 279