Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use GUID as parameter in one controller?

My goal is that I still want to use the default asp.net mvc id but I want to use Guid in one controller like this

http://example.com/MyController/Index/387ecbbf-90e0-4b72-8768-52c583fc715b

This is my route

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

MyController right now

public ActionResult Index(Guid guid)
{
return View();
}

Gives me the error

The parameters dictionary contains a null entry for parameter 'guid' of non-nullable type 'System.Guid' for method 'System.Web.Mvc.ActionResult Index(System.Guid)'

I guess it's because I have ID in routes? How can I use GUID as parameters in one controller but id in the rest of the application (as default)?

like image 433
Anders Avatar asked Feb 12 '16 13:02

Anders


1 Answers

Just change the name of the parameter from guid to id:

public ActionResult Index(Guid id)
{
    return View();
}

When binding the action, ASP.NET MVC inspects the types and the names of the action method and maps those to the parameters that are provided by the request. As the term id is used in the route, you have to name the parameter of the action accordingly.

like image 64
Markus Avatar answered Sep 28 '22 16:09

Markus