title: Sending ViewData to PartialView which is dynamically loaded using ajax call
body: <p>I am loading a _PartialView Dynamically to a view using Ajax call. And I want to send some view data in order to maintain state of that partial view in case some error occurs and page is posted back to itself and display the error message.</p>
  
  <p>Here is my ajax code on the view which fires on change of a drop-down value selection...</p>
  
  <pre><code>$.ajax({
              type: 'POST',
              url: '@Url.Action("LoadReportMaterialPartialView")',
              //dataType: 'json',     // WHEN RETURNING PARTIAL VIEW THIS LINE IS NOT REQUIRED...
              dataType: 'html',
              data: { LocationID: $("#ReportTransactionData_LocationID").val() },
              cache: false,
              success: function (data) {
                  // Clear old div content first...
                  $("#divReportMaterialDynamic").empty();
                  $("#divReportMaterialDynamic").append(data);
              },
              error: function (ex) {
                  alert('Please select a valid location.' + ex.error);
              }
          });
  </code></pre>
  
  <p>Function in the controller is as below: </p>
  
  <pre><code>public PartialViewResult LoadReportMaterialPartialView(string LocationID)
      {
          if (LocationID == string.Empty)
              LocationID = "0";
          Int32 intLocationID = Convert.ToInt32(LocationID);
  
          IList&lt;MaterialMaster&gt; ReportMaterials = GeneralRepository.GetAllMaterialByLocationAndCompanyID(intLocationID, CompanyID);
  
          return PartialView("_ReportMaterialPartialView", ReportMaterials);
      }
  </code></pre>
  
  <p>Code where I am setting ViewData Values in case of self page postback Action method is as below:</p>
  
  <pre><code>public ActionResult Create(ReportTransactionDataViewModel reportTransactionDataViewModel)
      {
          // Add default logged-in company ID...
          reportTransactionDataViewModel.ReportTransactionData.CompanyID = CompanyID;
  
          ReportTransactionData reportTransactionData;
  
          using (TransactionScope transaction = new TransactionScope())
          {
              try
              {
                  // Manage Site Name and Site Address...
                  SiteMaster siteMaster = GeneralRepository.IsSiteNameExist(reportTransactionDataViewModel.ReportTransactionData, CompanyID);
                  if (siteMaster != null) // If site already exist in the database...
                  {
                      reportTransactionDataViewModel.ReportTransactionData.SiteID = siteMaster.SiteID;
                  }
                  else
                  {
                      // Add New Site Address to the SiteMaster and Set new SiteID to the Transaction...
                      SiteMaster oSiteMaster = new SiteMaster();
                      oSiteMaster.SiteName = reportTransactionDataViewModel.ReportTransactionData.Site_Name.ToUpper();
                      oSiteMaster.SiteAddress = reportTransactionDataViewModel.ReportTransactionData.Site_Address.ToUpper();
                      oSiteMaster.CityID = reportTransactionDataViewModel.ReportTransactionData.CityID;
                      oSiteMaster.LocationID = reportTransactionDataViewModel.ReportTransactionData.LocationID.Value;
                      oSiteMaster.CompanyID = CompanyID;
                      oSiteMaster.IsActive = true;
                      // Set New Site Master entry...
                      reportTransactionDataViewModel.ReportTransactionData.SiteMaster = oSiteMaster;
                  }
  
                  // To autofill drop-downs on the view in case of self post-back view/page...
                  ViewData["TechnicianID"] = reportTransactionDataViewModel.ReportTransactionData.TechnicianID.Value;
                  ViewData["EngineerID"] = reportTransactionDataViewModel.ReportTransactionData.EngineerID.Value;
                  ViewData["VerifierID"] = reportTransactionDataViewModel.ReportTransactionData.VerifierID.Value;
                  ViewData["CityID"] = reportTransactionDataViewModel.ReportTransactionData.CityID.Value;
                  ViewData["ReportTimeID"] = reportTransactionDataViewModel.ReportTransactionData.ReportTimeID.Value;
  
                  // Fill ReportTransactionData...on report creation for the first time by the admin...                
                  reportTransactionDataViewModel.ReportTransactionData.Technician_Name = GeneralRepository.GetTechnicianNameByID(reportTransactionDataViewModel.ReportTransactionData.TechnicianID.Value);
                  reportTransactionDataViewModel.ReportTransactionData.EngineerID = 0;
                  reportTransactionDataViewModel.ReportTransactionData.Engineer_Name = string.Empty;
                  reportTransactionDataViewModel.ReportTransactionData.VerifierID = 0;
                  reportTransactionDataViewModel.ReportTransactionData.VerifierName = string.Empty;
                  reportTransactionDataViewModel.ReportTransactionData.UserID = GeneralRepository.GetLoggedInUserIDByName(User.Identity.Name);    // Get userID based on UserName which is unique...
  
                  // Set fields to UpperCase...
                  reportTransactionDataViewModel.ReportTransactionData.Site_Name = reportTransactionDataViewModel.ReportTransactionData.Site_Name.ToUpper();
                  reportTransactionDataViewModel.ReportTransactionData.Site_Address = reportTransactionDataViewModel.ReportTransactionData.Site_Address.ToUpper();
                  reportTransactionDataViewModel.ReportTransactionData.CaseID = reportTransactionDataViewModel.ReportTransactionData.CaseID.ToUpper();
                  reportTransactionDataViewModel.ReportTransactionData.Remarks = GeneralRepository.GetRemarksByRemarksID(reportTransactionDataViewModel.ReportTransactionData.RemarksID).ToUpper();
                  reportTransactionDataViewModel.ReportTransactionData.Report_Time = GeneralRepository.GetReportTimeByReportID(reportTransactionDataViewModel.ReportTransactionData.ReportTimeID).ToUpper();
                  reportTransactionDataViewModel.ReportTransactionData.City_Name = GeneralRepository.GetCityNameByCityID(reportTransactionDataViewModel.ReportTransactionData.CityID).ToUpper();
                  reportTransactionDataViewModel.ReportTransactionData.Customer_Type = GeneralRepository.GetCustomerTypeNameByID(reportTransactionDataViewModel.ReportTransactionData.CustomerTypeID).ToUpper();
                  reportTransactionDataViewModel.ReportTransactionData.CallTypeName = GeneralRepository.GetCallTypeNameByID(reportTransactionDataViewModel.ReportTransactionData.CallTypeID).ToUpper(); // Call Type
                  reportTransactionDataViewModel.ReportTransactionData.OptionalTechComments =
                      reportTransactionDataViewModel.ReportTransactionData.OptionalTechComments == null ? string.Empty : reportTransactionDataViewModel.ReportTransactionData.OptionalTechComments.ToUpper();
                  reportTransactionDataViewModel.ReportTransactionData.JustifyMaterialRemarks =
                      reportTransactionDataViewModel.ReportTransactionData.JustifyMaterialRemarks == null ? string.Empty : reportTransactionDataViewModel.ReportTransactionData.JustifyMaterialRemarks.ToUpper();
                  if (reportTransactionDataViewModel.ReportTransactionData.Job_Type.Value)
                  {
                      reportTransactionDataViewModel.ReportTransactionData.JobTypeName = "SUPPORT";
                  }
                  else
                  {
                      reportTransactionDataViewModel.ReportTransactionData.JobTypeName = "INSTALLATION";
                  }
  
                  // Fill Date...
                  ViewBag.CurrentDate = reportTransactionDataViewModel.ReportTransactionData.CreationDate.Value.ToShortDateString();
  
                  // Manage Earthing Status...
                  if (Request.Form["ReportTransactionData.Earthing_Status.Value"].ToString() == "false")
                  {
                      reportTransactionDataViewModel.ReportTransactionData.Earthing_Status = false;
                  }
                  else if (Request.Form["ReportTransactionData.Earthing_Status.Value"].ToString() == "true,false")
                  {
                      reportTransactionDataViewModel.ReportTransactionData.Earthing_Status = true;
                  }
  
                  // Fill Report Materials...
                  reportTransactionDataViewModel.Materials =
                      GeneralRepository.GetAllMaterialByLocationAndCompanyID(reportTransactionDataViewModel.ReportTransactionData.LocationID.Value, CompanyID);
  
  
                  // Add new binding between ReportTransactionData and material...
                  foreach (MaterialMaster material in reportTransactionDataViewModel.Materials)
                  {
                      ReportMaterial reportMaterial = new ReportMaterial();
                      reportMaterial.ReportID = reportTransactionDataViewModel.ReportTransactionData.ReportID;
                      reportMaterial.MaterialID = material.MaterialID;
                      reportMaterial.CompanyID = CompanyID;
  
                      if (!string.IsNullOrEmpty(Request.Form["MaterialQty_" + material.MaterialID.ToString()]))
                      {
                          reportMaterial.MaterialQty = Convert.ToInt32(Request.Form["MaterialQty_" + material.MaterialID.ToString()]);
                          // To autofill Report Material Quantity on the view in case of self post-back view/page...
                          ViewData["MaterialQty_" + material.MaterialID.ToString()] = reportMaterial.MaterialQty.Value;
                      }                        
  
                      // Add new reportMaterial...
                      db.Entry(reportMaterial).State = EntityState.Added;
                      reportTransactionDataViewModel.ReportTransactionData.ReportMaterials.Add(reportMaterial);
                  }
  
                  reportTransactionDataViewModel = UploadImages(reportTransactionDataViewModel);
  
                  // Manage Report History Snapshot of the complete report...
                  ReportHistory reportHistory = new ReportHistory();
                  reportHistory.CompanyID = CompanyID;
                  reportHistory.ReportID = reportTransactionDataViewModel.ReportTransactionData.ReportID;
                  reportHistory.ReportHistorySequence = ReportHistorySequence;
                  reportHistory.ReportHistoryXML = SerializeObjectToXML(reportTransactionDataViewModel);
                  // Add new report history on creation of new report by the Admin...
                  db.Entry(reportHistory).State = EntityState.Added;
                  reportTransactionDataViewModel.ReportTransactionData.ReportHistories.Add(reportHistory);
  
                  // Duplicate CaseID/TACID Validation...
                  var boolFlagSaveReport = ValidateDuplicateReport(reportTransactionDataViewModel.ReportTransactionData);
                  // Out Station call validation...
                  var boolFlagCallTypeValidation = ValidateOutStationReport(reportTransactionDataViewModel.ReportTransactionData);
                  if (ModelState.IsValid &amp;&amp; boolFlagSaveReport &amp;&amp; boolFlagCallTypeValidation)
                  {
                      reportTransactionData = reportTransactionDataViewModel.ReportTransactionData;
                      db.ReportTransactionDatas.Add(reportTransactionData);
                      db.SaveChanges();
                      return RedirectToAction("Index");
                  }
              }
              catch (DbEntityValidationException dbEx)
              {
                  foreach (var validationErrors in dbEx.EntityValidationErrors)
                  {
                      foreach (var validationError in validationErrors.ValidationErrors)
                      {
                          Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                              validationErrors.Entry.Entity.GetType().FullName,
                              validationError.PropertyName,
                              validationError.ErrorMessage);
                      }
                  }
                  // Handle exception here and Log Error to file...
                  IsSuccess = false;
                  ViewBag.ErrorMessage = "Transaction failed. Please try again. If problem persists, contact system administrator.";
                  ViewBag.InfoMessage = "";
              }
              catch (Exception ex)
              {
                  ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling
                  IsSuccess = false;
                  ViewBag.ErrorMessage = "Transaction failed. Please try again. If problem persists, contact system administrator.";
                  ViewBag.InfoMessage = "";
              }
              finally
              {
                  // Fill Date...
                  ViewBag.CurrentDate = reportTransactionDataViewModel.ReportTransactionData.CreationDate.Value.ToShortDateString();
  
                  // Manage Earthing Status...
                  if (Request.Form["ReportTransactionData.Earthing_Status.Value"].ToString() == "false")
                  {
                      reportTransactionDataViewModel.ReportTransactionData.Earthing_Status = false;
                  }
                  else if (Request.Form["ReportTransactionData.Earthing_Status.Value"].ToString() == "true,false")
                  {
                      reportTransactionDataViewModel.ReportTransactionData.Earthing_Status = true;
                  }
  
                  ViewBag.LocationList = GeneralRepository.GetLocationsByCompanyID(CompanyID);
                  ViewBag.CallTypeList = GeneralRepository.GetCallTypeByCompanyID(CompanyID);
                  ViewBag.RemarksList = GeneralRepository.GetTechnicianRemarksByCompanyID(CompanyID);
                  ViewBag.CustomerTypeList = GeneralRepository.GetCustomerTypeByCompanyID(CompanyID);
                  ViewBag.CompanyList = new SelectList(db.CompanyMasters, "CompanyID", "CompanyName", CompanyID);  
  
                  // Mark the transaction status...
                  if (IsSuccess)
                  {
                      transaction.Complete();
                  }
                  else
                  {
                      transaction.Dispose();
                  }
              }
          }
          return View(reportTransactionDataViewModel);
      }
  </code></pre>
  
  <p>My Partial view code...</p>
  
  <pre><code>@model IEnumerable&lt;RAWOnlineWEB.Models.MaterialMaster&gt;
  @{
  Layout = null;
  }
  
  &lt;table class="table" style="width:100%;" cellpadding="5" cellspacing="0"&gt;
  &lt;tr&gt;
      &lt;th&gt;@Html.Label("Material Name", htmlAttributes: new { @class = "control-label col-md-6" })&lt;/th&gt;
      &lt;th&gt;@Html.Label("Material Quantity", htmlAttributes: new { @class = "control-label col-md-6" })&lt;/th&gt;
      &lt;th&gt;@Html.Label("Material Unit", htmlAttributes: new { @class = "control-label col-md-6" })&lt;/th&gt;
  &lt;/tr&gt;
  
  @foreach (var item in Model)
  {
      &lt;tr&gt;
          &lt;td&gt;
              @Html.LabelFor(modelItem =&gt; item.MaterialName, item.MaterialName, htmlAttributes: new { @class = "control-label col-md-6" })
          &lt;/td&gt;
          &lt;td&gt;
              @Html.TextBox("MaterialQty_" + item.MaterialID, ViewData["MaterialQty_" + item.MaterialID.ToString()] == null ? 0 : Convert.ToDouble(ViewData["MaterialQty_" + item.MaterialID.ToString()]), new { @class = "form-control col-md-6" })
              @Html.Hidden("MaterialID_" + item.MaterialID, item.MaterialID)
              @Html.ValidationMessageFor(modelItem =&gt; item.MaterialID, "", new { @class = "text-danger" })
          &lt;/td&gt;
          &lt;td&gt;
              @Html.LabelFor(modelItem =&gt; item.MaterialUnit, item.MaterialUnit, htmlAttributes: new { @class = "control-label col-md-6" })
          &lt;/td&gt;
      &lt;/tr&gt;
  }
  </code></pre>
  
  <p></p>