2

Ok so I have followed several tutorials about how to submit a form using Ajax.BeginForm() notation. Everything seems pretty straightforward. However, what I am noticing (as evident by the screenshots below), is that despite using ajax, it still redirects to display the result instead of replacing the content of the div. Why is this?

For reference, I've been following: Submit form using AJAX in Asp.Net mvc 4

CODE:

        @Html.ValidationSummary(true)
        @using (Ajax.BeginForm("Create", "Role", new AjaxOptions(){
            InsertionMode = InsertionMode.Replace,
            UpdateTargetId = "RoleCreateResult",
            HttpMethod = "POST"
        }))
        {
            @Html.AntiForgeryToken()
            <fieldset>
            <div class="form-group">
                <label class="col-md-2 control-label">Name</label> 
                <div class="col-md-10">
                    <input type="text" class="form-control" id="RoleName" name="RoleName" data-val-required="The Role name field is required." data-val="true" />
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" id="CreateRoleSubmit" class="btn btn-default" value="Save" />
                </div>
            </div>
            </fieldset>
        }
        <div id="RoleCreateResult"></div>

Controller Code:

    //
    // POST: /Role/Create
    [HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        try
        {
            var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            if (roleManager.RoleExists(collection["RoleName"]))
            {
                return Json("Role " + collection["RoleName"] + " already exists.", JsonRequestBehavior.DenyGet);
            }
            else
            {
                var role = new IdentityRole();
                role.Name = collection["RoleName"];
                roleManager.Create(role);
                return Json("Role " + collection["RoleName"] + " created successfully.",JsonRequestBehavior.DenyGet);
            }
        }
        catch (Exception ex)
        {
            return Json("Error occured: " + ex.Message, JsonRequestBehavior.DenyGet);
        }
    }

Rendered HTML:

<form id="form0" method="post" data-ajax-update="#RoleCreateResult" data-ajax-mode="replace" data-ajax-method="POST" data-ajax="true" action="/Role/Create">

    <input type="hidden" value="N2laLUmcoQ2yvbKwK40Sd6z1f56aZ2w_v0SQ-WfOcgCGnFaSAVNCkfjYatyU…E-NxRPPMueFOW4r-SVSpceGZX99iWsjpstd82URv4cRsNqbvf2UnJ0M1VWA2" name="__RequestVerificationToken"></input>
    <fieldset>
        <div class="form-group"></div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input id="CreateRoleSubmit" class="btn btn-default" type="submit" value="Save"></input>
            </div>
        </div>
    </fieldset>

</form>
<div id="RoleCreateResult"></div>

Screens:

redirect

Community
  • 1
  • 1
Kyle
  • 2,339
  • 10
  • 33
  • 67

1 Answers1

2

I would first make sure that your action returns a partial view (without seeing this I can't confirm it does):

public ActionResult Create()
{
    return PartialView("Create");
}

Failing that I would make sure that you have all your javascript references to jquery and jquery.unobtrusive-ajax and that they are loading correctly (no 404's):

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
hutchonoid
  • 32,982
  • 15
  • 99
  • 104
  • I've updated my question to include my controller. It does not return a partial view, it returns json – Kyle Jul 02 '15 at 15:30
  • @Kyle if you don't need json, you can just use `Content("")` result instead. It sounds like your javascript references are either not referenced or loaded. Have you checked that? – hutchonoid Jul 02 '15 at 15:43
  • Yes, that seems to have fixed it, my link was broken apparently. Although to speak to your other point. What is the difference of returning context vs json vs string etc. – Kyle Jul 02 '15 at 16:01
  • @kyle I just thought if you didn't need the data in Json format to just return the string. :) – hutchonoid Jul 02 '15 at 16:30
  • Ok that makes sense. Thank you. – Kyle Jul 02 '15 at 18:04