2016-08-04 60 views
1

我想從jQuery代碼調用控制器操作方法,但不知何故它不工作。以下是從JavaScript代碼:從jQuery調用ASP.MVC操作方法

$(document).ready(function() { 
    $("#sendOTPSubmit").click(function() { 
     $.ajax({ 
      url: 'Controllers/RegisterSurfaceController/SendOTP', 
      success: function(data) { 
       alert(data); 
      }, 
      statusCode: { 
       404: function(content) { 
        alert('cannot find resource');  
       }, 
       500: function(content) { 
        alert('internal server error'); 
       } 
      },  
      error: function(req, status, errorObj) { 
       // handle status === "timeout" 
       // handle other errors 
      } 
     }); 
    }); 
}); 
[HttpPost] 
public JsonResult SendOTP() 
{    
    CardHolder user = new CardHolder(); 
    return Json(""); 
} 

我收到以下錯誤:

http://localhost:49289/Controllers/RegisterSurfaceController/SendOTP 404 (Not Found)

+0

$ .ajax({0}} {url:'Controllers/RegisterSurfaceController/SendOTP',輸入:「POST」, – SilentTremor

回答

2

首先,你有你的行動[HttpPost]屬性,所以你需要添加type: 'POST'$.ajax選項。另外,除非你定義了一個名爲'Controllers'的區域,否則你不應該在URL中需要該目錄,而且你也不需要'Controller'後綴。儘量只:url: '/RegisterSurface/SendOTP',,像這樣:

$.ajax({ 
    type: 'POST', 
    url: 'RegisterSurface/SendOTP', 
    success: function (data) { alert(data); }, 
    statusCode: { 
     404: function (content) { alert('cannot find resource'); }, 
     500: function (content) { alert('internal server error'); } 
    }, 
    error: function (req, status, errorObj) { 
     // handle status === "timeout" 
     // handle other errors 
    }   
}); 

還要注意的是,如果這上面的代碼可以剃鬚刀的範圍內運行,那麼你可以使用Url.Action助手爲您生成的網址:

url: '@Url.Action("SendOTP", "RegisterSurface")', 
+0

謝謝麥克羅斯,你的解決方案工作。 –

+0

沒問題。如果有幫助請記得upvote /接受答案 –

+0

我發送數據到函數? –