Skip to main content
 首页 » 编程设计

c#之使用 MVC Controller 作为 webService

2024年02月23日31lautakyan007

这是我的项目层次结构:

我正在尝试从 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 

但我在 chrome 控制台中收到以下错误:

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

1) 正确的路径应该是什么?

2) 连接到我的 get 请求末尾的 &_=1324071607446 是什么?

更新

我的 Controller 看起来像:

  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

请您参考如下方法:

基本的 MVC url 掩码如下:

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

以你的例子我们有:

'/manager/getLocations?userId=1234' 

Controller 应具有以下代码(示例):

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

现在您需要一个 View 文件来显示内容。创建一个名为“View”的文件夹(在项目的根目录中),并在其中创建另一个名为 Controller (Manager)的文件夹,并创建一个名为“GetLocations.aspx”的 View 文件(我们想要要求渲染)。

在 View 中打印 UserId 变量:

<%= ViewData["UserId"] %> 

如果它不起作用,您最好阅读大量有关 MVC 模式的内容。你可以开始here .