How to correctly use Partial views with Ajax Begin form How to correctly use Partial views with Ajax Begin form ajax ajax

How to correctly use Partial views with Ajax Begin form


I would refactor the views moving the ajax form outside the partial. That way the full partial which is rendered inside the form is refreshed on ajax posts, keeps unaware and decoupled of container structure and every view has their own responsibility:

Index.cshtml

<div class="panel panel-default">    <div class="panel-heading">        @using (Ajax.BeginForm("CreateOrEditPresupuestoGeneralxx", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "form-content", InsertionMode = InsertionMode.Replace }))        {            <div id="form-content">                @Html.Partial("CreateOrEditPresupuestoGeneralxx", Model)            </div>        }    </div></div>

CreateOrEditPresupuestoGeneralxx.cshtml

@using xx.Relacionamiento.Modelo.Bussiness.Entities.Enumeraciones;@using xx.Relacionamiento.Modelo.Bussiness.Entities;@using Kendo.Mvc.UI;@model PresupuestosGenerale@Html.HiddenFor(h => h.PresupuestoGeneralId)@Html.Hidden("Categoria",CategoriaEvento.xx.ToString())<div class="row">...


Here is one of the example that I used in some of my projects. In this example not only PartialView is rendered, also a DropdownList value is passed to the PartialView and displayed on it.

View :

<div id="divPartialView">    @Html.Partial("~/Views/MyPartialView.cshtml", Model)</div>$(document).ready(function () {     $(".SelectedCustomer").change(function (event) {        $.ajax({            url: '@Url.Action("GetPartialDiv", "Home")',            data: { id: $(this).val() /*add other additional parameters */ },            cache: false,            type: "POST",            dataType: "html",            success: function (data, textStatus, XMLHttpRequest) {                SetData(data);            },            error: function (data) { onError(data); }        });    });    function SetData(data) {        $("#divPartialView").html(data); //HTML DOM replace    } });


Controller :

[HttpPost]public PartialViewResult GetPartialDiv(int id /* ddl's selectedvalue */){    Models.GuestResponse guestResponse = new Models.GuestResponse();    guestResponse.Name = "this was generated from this ddl id:";     return PartialView("MyPartialView", guestResponse);}

Hope this helps...