Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net MVC 4 submit from with ajax call

I have this in the controller:

[HttpPost]
    public ActionResult Create(Student student)
    { //somecode..

and i want to submit this from:

<form method="post" action="/student/create"> 
<!-- the from contents-->

how to submit this from using Ajax call i need the JQuery ajax call that lets this form submitted.

and i want to make sure about datatype , thanks

like image 911
Muath Avatar asked Nov 12 '13 08:11

Muath


3 Answers

try this

var form = $('#formId');
$.ajax({
  cache: false,
  async: true,
  type: "POST",
  url: form.attr('action'),
  data: form.serialize(),
  success: function (data) {
    alert(data);
 }
});
like image 198
Mohit Kumar Avatar answered Nov 11 '22 05:11

Mohit Kumar


Use this, assuming you are using razor views:

@using (Ajax.BeginForm(new AjaxOptions(){
HttpMethod = "POST",
    Url = "your controller",
    OnComplete = "some client event"
})
{
    <fieldset>
        <legend>This is a demo form.</legend>
        @Html.LabelFor(model => model.Name)
        @Html.TextBoxFor(model => model.Name)

        <input type="submit" value="Save" />
    </fieldset>
}
like image 37
Besher Avatar answered Nov 11 '22 04:11

Besher


Well it would look something like (that's without looking at your view bindings):

// serialize your form into JSON - maybe you have a different method of doing it
var serializedForm = $("#YourFormId").serialize();

// post it to the server
$.post("/student/create", serializedForm)
    .done(function (response) { 
       // it's done
    })
    .fail(function (xhr, status, error) { 
       // something bad happened
    });
like image 40
Dimitar Dimitrov Avatar answered Nov 11 '22 04:11

Dimitar Dimitrov