2011-12-16 53 views
1

這裏是我的項目hirarchy:使用MVC控制器作爲web服務

enter image description here

從browser.js我想打電話給ManagerController:

$("#jstree").jstree({ 
     "json_data": { 

    "ajax": { 


       type: "GET", 
       async: true, 
       "url": "Controllers/Manager/Getlocations?userId='1234'", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       cache: false, 
       success: function (msg) {       
         return msg; 
       }, 
       error: function() { 
        // TODO process error 
       } 
      }, 

//continuation is less relevant 

但我得到的鍍鉻以下錯誤控制檯:

GET http://localhost:1186/MainUgi/Controllers/Manager/Getlocations?userId= '1234' & _ = 1324071607446 404(未找到)

1)什麼應該是在正確的道路?

2)什麼是&_=1324071607446這是concacinated到我的請求結束?

更新

我的控制器看起來像:

public class ManagerController : Controller 
    { 

     public JsonResult GetLocations(string userId) 
     { 
      var locationsJson = 
      new {[ {"data": "[0]", .. some data...} ]}; 

      return Json(locationsJson, JsonRequestBehavior.AllowGet); 
     } 

我的要求是這樣的:

Request URL:http://localhost:1186/MainUgi/Controllers/Manager/Getlocations?userId=1234 
Request Method:GET 
Status Code:404 Not Found 
Request Headersview source 
Accept:application/json, text/javascript, */*; q=0.01 
Accept-Charset:windows-1255,utf-8;q=0.7,*;q=0.3 
Accept-Encoding:gzip,deflate,sdch 
Accept-Language:he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4 
Connection:keep-alive 
Content-Type:application/json; charset=utf-8 
Host:localhost:1186 
Referer:http://localhost:1186/MainUgi/browser.htm 
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7 
X-Requested-With:XMLHttpRequest 
Query String Parametersview URL encoded 
userId:1234 
Response Headersview source 
Cache-Control:private 
Connection:Close 
Content-Length:2346 
Content-Type:text/html; charset=utf-8 
Date:Fri, 16 Dec 2011 22:00:37 GMT 
Server:ASP.NET Development Server/10.0.0.0 
X-AspNet-Version:4.0.30319 

TIA

回答

2

基本MVC URL面膜如下:

/{CONTROLLER}/{ACTION}?{...PARAMETERS} 

你的榜樣,我們有:

'/manager/getLocations?userId=1234' 

而且控制器應具有以下代碼(例如):

[ControllerAction] 
public void getLocations(int userId) { 
    ViewData["UserId"] = userId; 
    RenderView("GetLocations"); 
} 

現在您需要有一個視圖文件來顯示內容。創建一個名爲「View」的文件夾(在項目的根目錄中),並在其中創建另一個文件夾(控制器名稱),並創建一個名爲「GetLocations.aspx」的視圖文件(我們想要求呈現)。

要打印的用戶ID變量視圖:

<%= ViewData["UserId"] %> 

如果它不工作,這是更好地爲你讀了很多關於MVC模式。你可以開始here

+0

我試圖僅使用控制器作爲webService。不是整個MVC模式 – 2011-12-16 22:03:48

+0

也許你需要定義路線...... – 2011-12-16 22:11:47

2

希望這將有助於:

  1. 嘗試從userId='1234'去掉單引號 - >userId=1234
  2. _=1324071607446參數的jQuery附加一個時間戳請求URL的末尾以防止緩存(請注意您如何使用cache: false)。
+0

1沒有幫助。相同404 – 2011-12-16 21:58:13

0

嘗試url和數據分離成兩個獨立的命令:

url: "Controllers/Manager/Getlocations", 
data: { userId: '1234' } 

還嘗試標記方法爲[HTTPGET]的情況下,你有方法超載。