N
N
Nposk2016-05-18 08:37:39
ASP.NET
Nposk, 2016-05-18 08:37:39

How to make URL from parameters in ASP?

Good afternoon.
A bit of theory: By default, the
route looks like this:
/Users/Add/Alex/120
Controller / Method / Parameter / Parameter
Is it possible to exclude the "Method" from this bundle by replacing it with a parameter, but so that the controller perceives it as a method with a parameter?
As a result, you need to get
/Users/Alex/120
with the action "Add"

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aram Aramyan, 2016-05-18
@Nposk

There are default methods for this.
With standard routing, the method (act) is "Index" by default, but this can be changed in the routing configuration.

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

this is for the entire site in the Startup class. Pay attention to the fragment action = "Index"
You can either register a separate route for your controller in the same place or through attributes:
routes.MapRoute(
                name: "Users",
                url: "Users/{action}/{id}",
                defaults: new { action = "Add", id = UrlParameter.Optional }
            );

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

through attributes like this:
[Route]
    public ActionResult Add(int id) { … }
  
    [Route(“{Index}”)]
    public ActionResult Index() { … }

S
Sergey, 2016-05-18
@senal

If you use a WebAPI controller, then you can do this:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

      }
    }

public class UsersController : System.Web.Http.ApiController
{
    [HttpPost]
    public void Add(string id, int p1)
    {
    }
}

but the url should be /Users/Alex?p1=120 and the POST method (see the attribute, you can also GET, but not good with the GET method, add something) then id="Alex" p1=120

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question