views:

54

answers:

2

I would like to call my JsonResult after a pageload, not on a submit button. I have two BeginForm functions.

$("#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
   <% } %>
<% } %>
+1  A: 

You can't have a form within another form, that isn't valid HTML. So you'll need to just have a single form and then use the page load function to make the ajax call like so:

$(function() {
    // anything in here happens after the page loads
});
Jeff T
+2  A: 

First create your controller action:

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

    return Json(people);
}

Next you make an ajax call to get the json data:

<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>
Dismissile
I am not sure what I did wrong. I have the JsonResult function in the controller. The problem is passing from the javascript to the controller