2014-08-28 55 views
1

访问时命名的路由直接访问操作时没有发现,却发现我有一个名为路线:通过AJAX

routes.MapRoute(
    name: "OfficeByZipCode", 
    url: "RetrieveOffice/ZipCode/{zipcode}", 
    defaults: new { controller = "RLO", action = "RetrieveOfficeByZipCode" } 
    ); 

我检索动作中的指定路线:

public ActionResult RetrieveByZipCode(string zipCode) 
{ 
    try 
    { 
     Office obj = null; 
     string urlOffice; 
     //build a route dictionary that includes the zip code 
     RouteValueDictionary route = new RouteValueDictionary 
     { 
      {"zipcode", zipCode} 
     }; 
     //build the relative path for the route to retrieve JSON data 
     VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "OfficeByZipCode", route); 
     //combine the relative path with the site's root path 
     //use the config value rather than HttpContext.Current.Request.Url to overcome issues that arise from Load Balancers and SSL offloading 
     urlOffice = String.Concat(Properties.Settings.Default.RootUrl, vpd.VirtualPath); 
     //the rest of the code. not important for this example 

现在,我访问这个动作在以下两种方法之一:

一,通过AJAX,从不同的页面:

$.ajax({ 
    url: "Test/RetrieveByZipCode", 
    type: "POST", 
    data: JSON.stringify(formData), 
    dataType: "html", 
    contentType: "application/json; charset=utf-8", 
    success: function (data) { 
     $("#content").html(data); 
    }, 
    error: function (error) { 
     alert("Error"); 
    } 
}); 

二,通过浏览器直接:

http://localhost/RLOService/test/RetrieveByZipCode/92677 

当访问直接的动作,此行回来空:

VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "OfficeByZipCode", route); 

但是,要求通过AJAX同样的动作,当它工作得很好。

两者之间的明显区别是我正在通过POST(AJAX)访问,另一个通过GET(URL)访问。如果我将AJAX操作更改为GET,则会收到相同的错误。为什么这会有所作为?

+0

它期待一个网址为http://host..../RetrieveOffice/ZipCode/ {}邮政编码和你的直接URL犯规匹配用它 – HaBo 2014-08-28 20:07:16

+0

@HaBo:我不确定你的意思。这怎么解释POST和GET之间的行为差​​异? – 2014-08-28 22:47:40

回答

2

更改此网址,使邮政编码一个参数(例如,http://localhost/RLOService/test/RetrieveByZipCode?zipCode=92677