Search code examples
ajaxasp.net-mvc-3partial-viewspartial-page-refresh

mvc partial view ajax update returning the partial view as a page


I have a partial view that upon adding an item to the database needs to update.

The Index.cshtml:

@using (Ajax.BeginForm("Index", "WinEntry", new AjaxOptions { HttpMethod = "POST",      UpdateTargetId = "wingrid", InsertionMode = InsertionMode.Replace}))
{
    @Html.Partial("_winVenue")
    @Html.Partial("_singleWin")
}
<div id="wingrid">
    @Html.Partial("_wingrid")
</div>

The _singleWin has the submit button

The controller:

[HttpPost]
public ActionResult Index(Win win)
{
    win.dealerId = "1234567890";
    win.posterid = "chris";
    win.posttime = DateTime.Now;
    wem.addWin(win);
    IEnumerable<Win> w = wem.getVenueWins(win.venue,win.windate);
    return PartialView("_wingrid",w);
}

When the controller returns the partial view _wingrid it returns it as a new page and the behavior I am looking for is like an update panel inside the wingrid div.

Any help would be appreciated.


Solution

  • You already seem to be doing this thanks to the UpdateTargetId = "wingrid" option in your AJAX form. Just make sure that you clear values that you modify in your POST controller action form the modelstate. Otherwise HTML helpers could still use the old values:

    [HttpPost]
    public ActionResult Index(Win win)
    {
        ModelState.Remove("dealerId");
        win.dealerId = "1234567890";
        ModelState.Remove("posterid");
        win.posterid = "chris";
        ModelState.Remove("posttime");
        win.posttime = DateTime.Now;
        wem.addWin(win);
        IEnumerable<Win> w = wem.getVenueWins(win.venue,win.windate);
        return PartialView("_wingrid",w);
    }
    

    Also don't forget to include the jquery.unobtrusive-ajax.js script to your page if you want your Ajax.* helpers to work:

    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>