user2818430
user2818430

Reputation: 6029

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.

Upvotes: 0

Views: 2056

Answers (2)

user2818430
user2818430

Reputation: 6029

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 }
        );
    }
}

Upvotes: 0

T McKeown
T McKeown

Reputation: 12857

You are sending a JSON object to the controller, why not send 3 parameters? Otherwise your controller action really needs something like this to match your request:

public class DataClass{
   public string id;
   public string name;
   public string age;
}

Change your controller:

public async Task<ActionResult> MyAction(DataClass data)
{
   .... code here     
}

Upvotes: 2

Related Questions