سؤال

Let's say I have this form inside a dialog

<div id = "add-users">
   <form>
      <input type="checkbox" value="1">Jim<br>
      <input type="checkbox" value="2">Will
      <input type="submit" value="Add">
   </form>
</div>

When the submit button is clicked, is it possible to post the form using ajax? I don't want the whole page to post, just the dialog.

Thanks for helping

هل كانت مفيدة؟

المحلول

Sure. Give an Id to the submit button so that we can use that for jQuery selection later.

<input type="submit" id="ajaxSubmit" value="Add">

Now in javascript, listen for the submit button click and get the form and serialize it and send it to your action method.

$(function(){

   $("#ajaxSubmit").click(function(e){
      var _this=$(this);
      e.preventDefault();
      var _form=_this.closest("form");
      $.post("@Url.Action("Create","User")",_form.seriazlize(),function(result){
            //do something with the result
      });
  });

});

Assuming your action method parameter is good to receive the serialized form.

نصائح أخرى

You can Serialize your form and send to controller using AJAX.

View File **

$("button").on("click", function () {
var myform = $('form');
var fd = myform.serialize();
$.ajax({ type: 'POST',
         url: '@Url.Content("~/Controller/Action")',
         data: fd });
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top