jacobsowles
jacobsowles

Reputation: 3003

Controller returning PartialView overwriting entire View

I'm POSTing and trying to re-load a partial view with the new data using Ajax like this:

Index.cshtml

<div id="left-column">
    @Html.Partial("~/Views/Project/_ProjectList.cshtml", Model.ProjectList)
</div>

~/Views/Project/_ProjectList.cshtml

@using (Ajax.BeginForm("Create", "Project", new AjaxOptions
{
    HttpMethod = "POST",
    UpdateTargetId = "left-column"
}))
{
    <h3>Create a new project</h3>
    <div class="form-group">
        <label for="new-project-name">Name</label>
        <input type="text" class="form-control" id="new-project-name" name="Name" placeholder="Example" />
    </div>

    <button type="submit" class="btn btn-primary">Create Project</button>
    <a href="#" id="create-project-cancel" rel="modal:close">Cancel</a>
}

Then my Controller returns the PartialView after some db work:

[HttpPost]
public PartialViewResult Create(Project newProject)
{
    db.Projects.Add(newProject);
    db.SaveChanges();

    var projectList = db.ProjectLists.SingleOrDefault(pl => pl.Id == 1);

    return PartialView("~/Views/Project/_ProjectList.cshtml", projectList);
}

I would expect the _ProjectList partial view to load into the #left-column element with the new projectList passed in by the Controller, but instead, the entire View is being overwritten, so the entire body of the new HTML source looks basically like this:

<body>
    <!-- all the stuff from the _ProjectList partial -->
</body>

It's worth noting that after the partial view returns, the URL reads /Project/Create, which I wouldn't expect.

I've included jquery-validate and jquery-validate-unobtrusive, and the console isn't showing any errors, so that shouldn't be the problem.

Any idea what's going on?

Upvotes: 0

Views: 633

Answers (2)

jacobsowles
jacobsowles

Reputation: 3003

Benjy got it in a comment above. It was a jQuery version issue. I'm running 3.1.0, and jquery.unobtrusive-ajax stopped working with jQuery version 1.9.

Upvotes: 0

Shyju
Shyju

Reputation: 218722

When using Ajax.BeginForm helper method to do ajax form posting, you need to include the jquery.unobtrusive-ajax.js file as well. This file has the code to handle the submit button click event and send the form asynchronously rather than doing the normal form submit.

If you do not include this file, the form submit will be normal. My guess is that you missed to include this file and hence missing the ajaxified form submit experience.

So make sure to load this file after jQuery

@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

Here is the link to nuget page if you want to add this file via nuget package manager.

Upvotes: 1

Related Questions