Posting form without @HTML.Beginform and using Jquery(ajax) in asp.net MVC

后端 未结 3 554
梦如初夏
梦如初夏 2020-12-30 09:23

How can I fill out a form without using @HTML.Beginform and by using JQuery Ajax instead? Right now I tried:

    var postData = { form1: username, form2: pas         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-30 09:38

    When you're using @Html.BeginForm, the HTML output is:

    And when you submit that form, the browser handles it just like another page navigation (only using POST method) hence the response is loaded into the parent frame.

    But, when you're initiating an Ajax request, it's up to you to handle the response from the server (typically using a callback function).

    If you want to simulate the regular form submission behavior, it would be something like:

    $.ajax({
        type: "POST",
        url: '/Controller/Method',
        data: postData,
        dataType: "json",
        traditional: true,
        success: function(response)
        {
            document.body.innerHTML = response;
        }
    });
    

    This would not replace the entire page content with the response (only the BODY contents) but in most cases it will be fine.

提交回复
热议问题