2010-08-09 89 views
0

我想在页面加载后调用我的JsonResult,而不是提交按钮。我有两个BeginForm函数。如何从JavaScript调用JsonResult?

$("#loadTableForm").ready(function() { 
    //$.post($(this).attr("action"), $(this).serialize(), function(response) { 
}); 

<%using (Html.BeginForm()) {%> 
    //data 
    <%using (Html.BeginForm("LoadTable", "Home", FormMethod.Post, new { id = "loadTableForm" })) {%> 
     //Table here should be loaded after page is loaded 
    <% } %> 
<% } %> 
+0

我不是jQuery的专家,但我不认为你应该使用现成功能的常规元素,只是文件。当您想要在DOM加载时发生某些事情时使用它。 $(document).ready(function(){ $ .post(“/ home/foobar”,...); }); – Dismissile 2010-08-09 16:54:05

回答

2

首先创建您的控制器动作:

[HttpPost] 
public JsonResult GetData() 
{ 
    IList<Person> people = GetPeople(); 

    return Json(people); 
} 

接下来你做的Ajax调用来获取JSON数据:

<script type="text/javascript"> 
    $(document).ready(function() { 
    $.ajax({ 
      type:"POST", 
      url: "<%= Url.Action("GetData") %>", 
      data: "{}", // pass in data usually 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function(data){ 
       // TODO work with this data 
      } 
     }); 
    }); 
</script> 
+0

我不知道我做错了什么。我有控制器中的JsonResult功能。问题是从JavaScript传递到控制器 – MrM 2010-08-10 12:39:29

2

您不能在另一个窗体中有一个窗体,这不是有效的HTML。所以,你需要只是有一个单一的形式,然后使用页面加载功能,使Ajax调用就像这样:

$(function() { 
    // anything in here happens after the page loads 
});