2010-11-13 68 views
0

嗨 我是新來的MVC和jQuery,我遵循我在網上找到的例子,但我堅持 我有img元素在我的網頁上我試圖通過jQuery單擊事件添加,然後從我的控制器調用操作。.net MVC2 jQuery不能從控制器調用動作

我的頁面

<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server"> 
<h2>About</h2> 
<p> 
    Put content here. 
</p> 
<img id="img1" alt="some image" src="http://www.google.pl/logos/2010/stevenson10-hp.jpg" /> 

<script type="text/javascript" language="javascript"> 
    $("#img1").click(function (e) { 
     $.ajax({ 
      type: "POST", 
      url: "Home/CheckAge", 
      data: "{}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      async: true, 
      cache: false, 
      success: function (msg) { 
       alert("ok"); 
      }, 
      error: function (XMLHttpRequest, textStatus, errorThrown) { 
       alert(textStatus+" - "+errorThrown); 
      } 
     }); 
     return false; 
    });  
</script> 

事件被添加,但是當我點擊圖片我總是最後的誤差函數 並提醒說:「錯誤 - 未定義」

我的控制器看起來像這樣

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     ViewData["Message"] = "Welcome to ASP.NET MVC!"; 
     return View(); 
    } 

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

    public static string Test() 
    { 
     string name = "aaa"; 
     return "Hello " + name; 
    } 

    [HttpPost] 
    public JsonResult CheckAge(String code) 
    { 
     return Json("abc"); 
    } 
} 

我試過很多組合和很多例子,但結果總是一樣的 任何想法我在做什麼錯? 我使用的Visual Web Developer 2010速成

THX你的建議

回答

3

你CheckAge方法需要一個參數:

[HttpPost] 
public JsonResult CheckAge(String code) 
{ 
    return Json("abc"); 
} 

但你不傳遞參數在AJAX:

data: "{}", 

您還需要包裝腳本代碼在$(document).ready()

$(document).ready(function() { 
    $("#img1").click(function (e) { 
     $.ajax({ 
      type: "POST", 
      url: "Home/CheckAge", 
      data: {code: "theCode"}, 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      async: true, 
      cache: false, 
      success: function (msg) { 
       alert("ok"); 
      }, 
      error: function (XMLHttpRequest, textStatus, errorThrown) { 
       alert(textStatus+" - "+errorThrown); 
      } 
     }); 
     return false; 
    }); 
}); 
0

您正在設置contentType = application/json作爲請求,但控制器上沒有任何東西可以理解這一點。默認模型聯編程序僅適用於標準查詢字符串參數(application/form-url-encoded)。所以,你可以試試這個:

$('#img1').click(function (e) { 
    $.ajax({ 
     type: 'POST', 
     url: '<%= Url.Action("CheckAge") %>', 
     data: { code: 'some code you want to send' }, 
     dataType: 'json', 
     cache: false, 
     success: function (msg) { 
      alert(msg.result); 
     }, 
     error: function (XMLHttpRequest, textStatus, errorThrown) { 
      alert(textStatus+" - "+errorThrown); 
     } 
    }); 
    return false; 
}); 

而控制器動作:

[HttpPost] 
public ActionResult CheckAge(string code) 
{ 
    return Json(new { result = "abc" }); 
} 

注意將contentType如何不再使用,數據散列包含將被髮送到控制器動作的代碼參數該網址不再硬編碼,但使用網址助手來計算它。此外,控制器操作使用匿名對象返回JSON。

相關問題