Pass existing model into AJAX PartialViewResult
- by Joe
I’m using AJAX to asynchronously update a partial view and need to pass the existing model into the partial view.
Controller Action
public ActionResult Edit(int id)
{ var vM = new MyViewModel(); // vM is viewModel
return View(vM); }
Edit View
@using (Html.BeginForm())
{ @Html.ValidationSummary(true)
...
<span id = "Ship"> @Html.Partial("AJAX_Views/_Ship")</span>
_Ship Partial View
@model MyProject.ViewModels.MyViewModel
<table class="detailtable" style="min-width:398px"> <tr> <th style="padding-left:132px" colspan="2">
<span class="editor-label">Shipping Address</span> <span class="editor-label" style="padding-left:55px">
@Ajax.ActionLink("Delete", "SHIPDEL", new AjaxOptions { UpdateTargetId = "Ship", InsertionMode = InsertionMode.Replace, HttpMethod = "Get" })</span>
<tr><th style="min-width:152px"><span class="editor-label">Street:</span></th> @Html.HiddenFor(m => m.CmpAdrsSh.Id) @Html.HiddenFor(m => m.CmpAdrsSh.CompPersonId)
@Html.HiddenFor(m => m.CmpAdrsSh.IsShip)
<td><span class="editor-field">@Html.EditorFor(m => m.CmpAdrsSh.Street) @Html.ValidationMessageFor(m => m.CmpAdrsSh.Street) </span></td></tr>
<tr><th><span class="editor-label">City:</span></th>
<td><span class="editor-field">@Html.EditorFor(m => m.CmpAdrsSh.City) @Html.ValidationMessageFor(m => m.CmpAdrsSh.City) </span></td></tr>
<tr><th><span class="editor-label">State:</span></th>
<td><span class="editor-field">@Html.DropDownList("CmpAdrsSh.State", (IEnumerable<SelectListItem>)ViewBag._State) @Html.ValidationMessageFor(m => m.CmpAdrsSh.State) </span></td></tr>
<tr><th><span class="editor-label">Zip:</span></th>
<td><span class="editor-field">@Html.EditorFor(m => m.CmpAdrsSh.Zip) @Html.ValidationMessageFor(m => m.CmpAdrsSh.Zip) </span></td></tr>
_ShipDel Partial View
@model MyProject.ViewModels.MyViewModel
<table class="detailtable" style="min-width:398px"> <tr> <th style="padding-left:132px" colspan="2">
<span class="editor-label">Shipping Address</span>
<span class="editor-label" style="padding-left:10px; color:red">Marked for Deletion.</span></th></tr>
<tr><td>To not Delete Select Cancel below!</td></tr>
@Html.HiddenFor(m => m.CmpAdrsSh.Street) @Html.HiddenFor(m => m.CmpAdrsSh.City)
@Html.HiddenFor(m => m.CmpAdrsSh.State) @Html.HiddenFor(m => m.CmpAdrsSh.Zip)
Controller PartialViewResult Action
public PartialViewResult SHIPDEL() { return PartialView("AJAX_Views/_ShipDel"); }
I tried adding this.ModelState to the Action but then the view will not render. I'm guessing I somehow have to pass the model to the SHIPDEL Action first. I couldn't find an @Ajax.ActionLink overload that would allow this.
public PartialViewResult SHIPDEL() { return PartialView("AJAX_Views/_ShipDel", this.ModelState); }
In the _ShipDel Partial View I need to expose the CmpAdrsSh properties so the model validates in the POST Action. The model is empty at this point. How do I pass the existing vM model into the _ShipDel partial view?
Thank you,