2012-02-08 50 views
0

如何在Controller中創建一個方法,使其成爲AJAX Callable?如何在MVC控制器中創建一個方法,使其成爲AJAX Callable?

例如,代碼爲{0}可以使用訪問{1}時返回類型是的ActionResult:

{0}: 
public ActionResult TestWithActionResult(string id) 
     { 
      return View(); 
     } 

{1}: 
http://localhost:4574/ControllerName/TestWithActionResult/2 

但我的下面的代碼{3}不能與{4}訪問:

{3}: 
    public string TestWithString(string id) 
      { 
       return "some string"; 
      } 
{4}: 
http://localhost:4574/ControllerName/TestWithString/2 

當我打開{4}時,{3}中的ID始終爲空。

我應該用不同的方式裝飾{3}嗎?怎麼樣?

感謝,

回答

1

嘗試使用JsonResult:

public JsonResult TestWithActionResult(string id) 
{ 
    return Json("Some string"); 
} 

編輯:

可以調用使用AJAX這樣的(使用jQuery)

$.ajax( 
    url: 'http://localhost/TestWithActionResult/feed1', 
    type:'GET', 
    dataType: 'json', 
    success: function(data) { 
     //Process data 
    }, 
    error: function(error) { } 
); 
+0

你會如何使用AJAX從客戶端調用它? – 2012-02-08 15:35:51

+0

你會如何用@ Html.RenderAction(「TestWithActionResult」)來調用它?你需要傳遞參數給它。 – 2012-02-08 17:27:31

0

你的方法需要返回某種類型的ActionResult(或ViewResultJsonResult等)需要考慮的行動。您可以使用JsonResult將文本寫入響應。

public ActionResult TestWithActionResult(string id) 
{ 
    return new Json("some string"); 
} 
+0

我返回布爾函數,它爲我工作。你爲什麼這麼說? – gdoron 2012-02-08 15:20:01

+0

JsonResult類是無參數的。 – 2012-02-08 15:34:55

+0

@William剛剛返回'Json(「一些字符串」)' – scottm 2012-02-08 15:49:34

相關問題