2015-07-18 10 views
0

我有一個jQuery的$ .getJson調用控制器操作,返回一個json。多個參數之一的c#url動作爲空

動作接受3個參數:

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

和在JavaScript

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

的問題是,在動作僅ID和名稱值被提供的age is null。年齡值是。如果我只在頁面

@ Model.Age

上顯示年齡,則顯示值...不知道如何設置爲該操作。

路徑看起來像這樣:

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

基本上只有第一2個參數被髮送到動作。第三個是空的。我有一種感覺是這裏的路線問題,但無法弄清楚。

回答

0

其實我加入了新的途徑,以我的RouteConfig.cs類解決了這個:

現在看起來像這樣。請注意,新的名字和年齡參數:

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

您正在向控制器發送JSON對象,爲什麼不發送3個參數?否則,你的控制器動作確實需要這樣的事,以符合您的要求:

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

更改您的控制器:

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

我只是實現這個,第三個還是空... – user2818430

+0

那麼它越來越設置爲空 –

+0

你爲什麼不顯示你的js Model類?在發送數據進行驗證之前,還需要放置一個「調試器」行。 –