using pjax to submit a form

PlTaylor picture PlTaylor · Mar 8, 2012 · Viewed 9.6k times · Source

I have form on my page that has the following code

<form class="form">
    ... bunch of inputs and presentation logic...
    <div>
        <input type="submit" class="btn btn-primary" id="submit_btn" value="Save Part"/>
        <a class="btn" href="/Part/CopyPart/[email protected] ">Copy Part</a>
        <a class="btn" href="/Part/Delete/[email protected]">Delete Part</a>
        <a class="btn" href="/Part/PartList/[email protected]">Return To Part List</a>
    </div>
    @Html.HiddenFor(model => model.ID)
    @Html.HiddenFor(model => model.Manufacturer)
    @Html.HiddenFor(model => model.DateCreated)
    @Html.HiddenFor(model => model.Manufacturer)
    @Html.HiddenFor(model => model.IsActive)
    @Html.HiddenFor(model => model.PartType)
</form>

and I am trying to use pjax() to submit this form and refresh the containing with some results. My js code is as follows.

$(function() {
    $('a').pjax({ container: "#update_panel", timeout: 2000 }).live('click', function() {});
    $("#submit_btn").click(function() {
        var form = $('#form');
        $.pjax({
            container: "#update_panel", 
            timeout: 2000,
            url: "@Url.Action("UpdatePart","Part")",
            data: form.serialize()
        });
    });
});

This code submits calls my UpdatePart() action but it passes an empty model to the action? How can I populate the model with the form contents so that it all works?

Answer

Ricky Levi picture Ricky Levi · Feb 24, 2015

I see in their docs: https://github.com/defunkt/jquery-pjax That they have a simple way to do it:

<div id="pjax-container">
</div>

<form id="myform" pjax-container>
 ... all inputs/submit/buttons etc ....
</form>

<script>
$(document).on('submit', 'form[pjax-container]', function(event) {
  $.pjax.submit(event, '#pjax-container')
})
</script>

I personally didn't see this example before .. maybe it's new/not ... but hope it will help others.