How to submit a form via Ajax in ASP.NET MVC?

I have a view consisting of several partial views, one of which displays user information with a button Edit.

When the button is pressed Edit, I make an ajax call to another Actionthat returns Partial View, which is loaded into the JQuery-UI modal dialog.

How to submit this edit form via Ajax and update the partial view UserInfoon the main page?

+3
source share
2 answers

Ajax call

$('#submitIt').submit(function() {
    var createdBy = $('#createdBy').val();
    $.ajax({
         type: "POST",
         url: '/MyController/GetContact/',
         dataType: "html",
         data: { 'createdBy': createdBy },
         success: function (result) {
            $('#myLittleForm').html(result);
         },
         error: function (request, status, error) {
              //Do Something on Failure
         }
     });
});

controller

    [HttpPost]
    public ActionResult GetContact(string createdBy)
    {
         ViewData["CreatedBy"] = createdBy;
         return PartialView("MyView");
    }

Markup

<div id="myLittleForm">
   <form action="/MyController/GetContact/" method="post">
      <input id="createdBy" type="text"/> <br/>
      <input id="submitIt" type="submit" value="Submit"/>
   </form>
</div>

Note

When you submit the form under the markup, an ajax call is made, and the div "myLittleForm" is replaced by a partial view.

+6
source

: oops, - Ajax, :

< script src= "../../Scripts/MicrosoftAjax.js" type = "text/javascript" > </ script >

< script src= "../../Scripts/MicrosoftMvcAjax.js" type = "text/javascript" > </ script >

< script src= "../../Scripts/AjaxLoadedContentScriptFix.js" type = "text/javascript" > </ script >

, script, , , , :)

Ajax.BeginForm , . AjaxOptions, , .. :

<% Ajax.BeginForm("FormName" , new { id = Model.SomeProperty }, 
       new AjaxOptions { UpdateTargetId = "MyDivToUpdate", OnSuccess = "onSuccess" }); %>
+2
source

Source: https://habr.com/ru/post/1788203/


All Articles