2011-07-02 55 views
2

我有這個JavaScript的一個ASP.Net MVC項目的頁面:Javascript和MVC返回類型

function showAllianceMembers_onclick() { 
    var strName = $("#allianceNameTextBox").val(); 

    $.ajax(
    { 
     type: "POST", 
     url: "/Alliance/Index", 
     data: "allianceName=" + strName, 
     success: function (result) { 
      if (result.success) { 
       alert("done!"); 
      } 
      else { 
       alert("error!!"); 
      } 
     }, 
     error: function (req, status, error) { 
      alert(error); 
     } 
    }); 
} 

如你所知,這個腳本調用MVC Action。這裏是MVC Action

[HttpPost] 
public ActionResult Index(string allianceName) 
{ 
    //Populating an object containing a list (IList) 

    return View(res); 
} 

這裏的問題是,JavaScript代碼只顯示與錯誤訊息... 什麼是錯在我的代碼警報?

回答

2

在您的控制器操作中,您不是發送JSON,而是一個簡單的視圖。因此result變量上沒有定義.success屬性。這是你的AJAX請求可能什麼樣子:

$.ajax({ 
    type: "POST", 
    url: "/Alliance/Index", 
    data: { allianceName: strName }, 
    success: function (result) { 
     // If you got so far the AJAX request succeeded, the result variable 
     // will contain the final HTML of the rendered view 
     alert("done!"); 
    }, 
    error: function (req, status, error) { 
     alert(error); 
    } 
}); 

,或者如果你想從你的控制器動作發送JSON:

[HttpPost] 
public ActionResult Index(string allianceName) 
{ 
    // populate the result   
    return Json(new { success = true, result = res }); 
} 

然後:

$.ajax({ 
    type: "POST", 
    url: "/Alliance/Index", 
    data: { allianceName: strName }, 
    success: function (result) { 
     if (result.success) { 
      // do something with result.res 
      alert("done!"); 
     } 
    }, 
    error: function (req, status, error) { 
     alert(error); 
    } 
}); 
+0

我應該改變'ActionResult'爲'JSonResult'? –

+2

@Dr TJ,不,你不應該。 Json方法返回一個JsonResult,它繼而從ActionResult派生。因此,爲了更通用,請在您的動作簽名中保留ActionResult。 –

1

我假設你正在嘗試檢索數據,而不是HTML標記。
試試這個:

$.ajax(
{ 
    type: "POST", 
    url: "/Alliance/Index", 
    data: { 'allianceName' : strName }, 
    dataType: 'json', 
    success: function (result) { 
     if (result.success) { 
      alert("done!"); 
     } 
     else { 
      alert("error!!"); 
     } 
    }, 
    error: function (req, status, error) { 
     alert(error); 
    } 
}); 

並更新此也:

[HttpPost] 
public JsonResult Index(string allianceName) 
{ 
    //Populating an object containing a list (IList) 

    return new JsonResult { Data = res }; 
} 
+0

他不會從他的操作中返回JSON,而是返回HTML的視圖。 –

+0

啊,你已經更新了你的答案,以考慮我的評論,消除我的downvote。 –

+1

@Darin,你不知道他實際上想要返回什麼。我有一種感覺實際上是問題 - 他試圖獲取一些數據,而是返回視圖。 – Kon