2013-01-05 34 views
0

我是ASP.NET MVC的新手。我想通過$.ajax調用控制器的方法,該方法不是視圖中的操作方法,但我在瀏覽器控制檯中出現錯誤。我想問一下,是不是可以通過ajax調用不是操作方法的方法。

代碼視圖

@{ 
    ViewBag.Title = "About Us"; 
} 
<script type="text/javascript"> 

    function ajaxcall() { 
     $.ajax({ 
      url: '/Home/ValidatePin', 
      type: 'Post', 
      success: function (result) { 
       alert(result.d); 
      } 
     }) 
    } 
</script> 
<h2>About</h2> 
<p> 
    Put content here. 

    <input type="button" onclick="ajaxcall()" value="clickme" /> 
</p> 

這裏是我的方法

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Services; 
namespace MvcApplication1.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      ViewBag.Message = "Welcome to ASP.NET MVC!"; 

      return View(); 
     } 

     public ActionResult About() 
     { 
      return View(); 
     } 

     [WebMethod] 
     public static string ValidatePin() 
     { 
      return "returned from controller class"; 
     } 
    } 
} 
+0

'我在瀏覽器控制檯中出錯'它是什麼? – Musa

+0

我的意思是通過f12進行調試的錯誤 – user1929135

回答

0

代碼控制器的所有公共方法是行動,除非標有NonAction屬性。

[WebMethod]屬性來自ASP.NET web服務(非MVC),並且在MVC控制器中沒有效果。

您的ValidatePin方法未被調用,因爲它是靜態的。 Action方法必須是實例方法。

+0

感謝是真的有幫助 – user1929135

+0

但是有必要創建一個方法與returntype actionresult – user1929135

+0

@ user1929135不,它不是。如果你真的想要一個字符串,一個'string'就可以做到。 – GSerg