asp.net MVC 4 submit from with ajax call

前端 未结 3 1055
长发绾君心
长发绾君心 2021-01-12 21:57

I have this in the controller:

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

and i want to submit this from

相关标签:
3条回答
  • 2021-01-12 22:31

    try this

    var form = $('#formId');
    $.ajax({
      cache: false,
      async: true,
      type: "POST",
      url: form.attr('action'),
      data: form.serialize(),
      success: function (data) {
        alert(data);
     }
    });
    
    0 讨论(0)
  • 2021-01-12 22:37

    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>
    }
    
    0 讨论(0)
  • 2021-01-12 22:44

    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
        });
    
    0 讨论(0)
提交回复
热议问题