开发者

How do I call a JsonResult from javascript?

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

$("#loadTableForm").ready(function() {
    //$.post($(thi开发者_如何学JAVAs).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
   <% } %>
<% } %>


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>


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
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜