1

I have a controller with 2 actions:

public class OrganizationUnitsController : Controller
{
    public ActionResult Create()
    {
        // return empty form
        return View();
    }

    [HttpPost]
    public ActionResult Save(OrganizationUnitViewModel unitViewModel)
    {
        // Save the new unit to the DB
        return View();
    }
}

The Create.cshtml is:

@using (Html.BeginForm("Save", "OrganizationUnits", FormMethod.Post, new { @id = "form", @class = "form-horizontal" }))
{

    <!-- Some inputs -->

    <a href="" class="btn btn-primary">Save</a>
}

$('#form')
.on('submit',function (e) {
        e.stopPropagation();

        $.ajax({
            url: '@Url.Action("Save", "OrganizationUnits")',
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                      Name: $('#Name').val(),
                      Admin: JSON.stringify({ 'FullDescription': $('#Admin').val() }),
                      Members: JSON.stringify( $('#users_list_box').val() )
            });
});

The problem is when i click the save button, the javascript code which makes the unitViewModel and pass the form to Save action not invoked and the Create action is invoked.

Changing the controller action in the @Html.BeginForm() to null doesn't solved the problem.

How can i fix it?

Ehsan Toghian
  • 548
  • 1
  • 6
  • 26

2 Answers2

1

Stephen Muecke's correct <a href="" class="btn btn-primary">Save</a> is problematic, and click on it causes a GET, try replacing it with submit input type.

<input type="submit" class="btn btn-primary" value="Save" />

and use e.preventDefault(); because stopPropagation stops the event from bubbling up the event chain, whereas preventDefault prevents the default action the browser makes on that event.

$('#form').on('submit',function (e) {
    var actionUrl = this.action;
    e.stopPropagation();
    e.preventDefault();
    $.ajax({
        url: actionUrl,
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
                  Name: $('#Name').val(),
                  Admin: JSON.stringify({ 'FullDescription': $('#Admin').val() }),
                  Members: JSON.stringify( $('#users_list_box').val() )
        });
});
manish
  • 1,450
  • 8
  • 13
0

This may not be YOUR cause, but I encountered the same problem.

My problem was that there was an [Authorize] attribute on the controller but the action called did not have the [AllowAnonymous] attribute.

Mike
  • 419
  • 4
  • 6