将ViewData发送到使用ajax调用动态加载的PartialView

时间:2015-11-18 18:17:48

标签: ajax asp.net-mvc-5 asp.net-mvc-partialview viewdata

我正在使用Ajax调用动态地将_PartialView加载到视图中。我想发送一些视图数据,以便在发生某些错误并将页面回发给自身并显示错误消息时保持该部分视图的状态。

这是我在视图上的ajax代码,它会触发下拉值选择的更改...

$.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);
            }
        });

控制器中的功能如下:

public PartialViewResult LoadReportMaterialPartialView(string LocationID)
    {
        if (LocationID == string.Empty)
            LocationID = "0";
        Int32 intLocationID = Convert.ToInt32(LocationID);

        IList<MaterialMaster> ReportMaterials = GeneralRepository.GetAllMaterialByLocationAndCompanyID(intLocationID, CompanyID);

        return PartialView("_ReportMaterialPartialView", ReportMaterials);
    }

我在自编页回发时设置ViewData值的代码操作方法如下:

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 && boolFlagSaveReport && 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);
    }

我的部分查看代码...

@model IEnumerable<RAWOnlineWEB.Models.MaterialMaster>
@{
Layout = null;
}

<table class="table" style="width:100%;" cellpadding="5" cellspacing="0">
<tr>
    <th>@Html.Label("Material Name", htmlAttributes: new { @class = "control-label col-md-6" })</th>
    <th>@Html.Label("Material Quantity", htmlAttributes: new { @class = "control-label col-md-6" })</th>
    <th>@Html.Label("Material Unit", htmlAttributes: new { @class = "control-label col-md-6" })</th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.LabelFor(modelItem => item.MaterialName, item.MaterialName, htmlAttributes: new { @class = "control-label col-md-6" })
        </td>
        <td>
            @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 => item.MaterialID, "", new { @class = "text-danger" })
        </td>
        <td>
            @Html.LabelFor(modelItem => item.MaterialUnit, item.MaterialUnit, htmlAttributes: new { @class = "control-label col-md-6" })
        </td>
    </tr>
}

0 个答案:

没有答案