Search code examples
c#asp.net-mvcasp.net-mvc-viewmodel

c# url action with multiple parameter one is null


I have a jquery $.getJson call to a controller action that returns a json.

The action accepts 3 parameters:

public async Task<ActionResult> MyAction(string id, string name, string age)
{
    .... code here     
}

and in JavaScript

$.getJson('@Url.Action("MyAction", "MyController", new { @id= Model.Id, @name=Model.Name, @age=Model.Age })')

The problem is that in the action only the Id and Name values are provided the age is null. The age value is ther. If I just display the age on the page

@Model.Age

the values is shown ... somehow is not set to the action.

The route looks like this:

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

Basically only the first 2 parameters are sent to action. The third one is null. I have a feeling is a route issues here, but cannot figure it out.


Solution

  • I actually solved this by adding a new route to my RouteConfig.cs class:

    Now it looks like this. Notice the new name and age parameters:

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
    
            routes.MapRoute(
                name: "UserRoute",
                url: "{
                         controller}/{action}/{id}/{name}/{age}",
                         defaults: new { 
                                        controller = "Home", 
                                        action = "Index", 
                                        id = UrlParameter.Optional, 
                                        name = UrlParameter.Optional, 
                                        age = UrlParameter.Optional }
            );
    
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { 
                                 controller = "Home", 
                                 action = "Index", 
                                 id = UrlParameter.Optional }
            );
        }
    }