-->
ZDIRY-TUFWT-EBONM-EYJ00-IDBLANTER.COM
ZDIRY-TUFWT-EBONM-EYJ00

BLANTERWISDOM105

JsonResult Return View dan Data Pada Waktu Yang Sama di ASP NET MVC

4/28/2020

Biasanya untuk mendapatkan view saat menggunakan Ajax biasanya menggunakan metode ActionResult seperti di bawah ini,

Controller:

private UploadExcel2Repo con = new UploadExcel2Repo();
        #region Search
        public ActionResult Search(UploadExcel2 data, int currentPage, int recordPerpage)//IList<UploadExcel2> listData
        {
            AjaxResult ajaxResult = new AjaxResult();
            try
            {
                //currentPage = 1;
                PagingModel pmodel = new PagingModel(con.getCount(data), currentPage, recordPerpage);
                ViewData["Paging"] = pmodel;

                IList<UploadExcel2> listData = con.getAllData(data, pmodel.Start, pmodel.End);
                ViewData["ListData"] = listData;
            }
            catch (Exception ex)
            {
                return Json("Error : " + ex.Message, JsonRequestBehavior.AllowGet);
            }
            return PartialView("_GridView", data);
        }
        #endregion

Script:

function myFunction(){
 function btnSearch_onClick(page) {
        //var page = 1;
        popUpProgressShow();
        $.ajax({
            type: "POST",
            url: "@Url.Content("~/UploadExcel2/Search")",
            data: {
                Name: $("#inputName").val(),
                Gender: $("#cmbGender").val(),
                recordPerPage: $("#recordPerPage").val(),
                currentPage: page
            },
            success: function (data) {
                $("#divGrid").html(data);
                //$("#divPaging").html(data);
                popUpProgressHide();
            },
            error: function (data) {
                popUpProgressHide();
            }
        });

Namun kali ini Agung Panduan akan menjelaskan bagaimana caranya return View dan Data secara bersamaan menggunakan JsonResult. Kuncinya ada pada pembuatan model AjaxResult yang menampung semua nilai yang diperoleh dan Metode ConvertViewToString.

Model:


using System;
using System.Collections.Generic;
using System.Linq;

namespace …Models
{
    public class BaseResult
    {
        public const string VALUE_SUCCESS = "SUCCESS";
        public const string VALUE_ERROR = "ERROR";

        public string Result { set; get; }
        public string ProcessId { set; get; }
        public string[] SuccMesgs { set; get; }
        public string[] ErrMesgs { set; get; }
        public object[] Params { set; get; }
        public object[] Params2 { set; get; }
        public string ViewHtml { set; get; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;

namespace …Models
{
    public class AjaxResult : BaseResult
    {
        public string ValueSuccess { get { return VALUE_SUCCESS; } }
        public string ValueError { get { return VALUE_ERROR; } }
    }
}

Controller:


#region GetByKey
        public JsonResult GetByKeyPaging(UploadExcel2 data, int currentPage, int recordPerPage)
        {
            AjaxResult ajaxResult = new AjaxResult();
            UploadExcel2 result = null;

            try
            {
                PagingModel pmodel = new PagingModel(QcGatRepo.SearchCount(data), currentPage, recordPerPage);
                ViewData["Paging"] = pmodel;

                result =  QcGatRepo.SearchPaging(data, pmodel.Start, pmodel.End);

                UploadExcel2 entities = new UploadExcel2 ();
                string viewContent = ConvertViewToString("_PaginatorBottom", pmodel);
                //return Json(new { PartialView = viewContent });
                ajaxResult.ViewHtml = viewContent;

                if (result == null)
                {
                    ajaxResult.Result = AjaxResult.VALUE_ERROR;
                    ajaxResult.ErrMesgs = new string[]{
                        string.Format("No Data With the selected key found, please refresh the screen first")
                    };

                    return Json(ajaxResult);
                }

                ajaxResult.Result = AjaxResult.VALUE_SUCCESS;
                ajaxResult.Params = new object[]{
                    result
                };            }
            catch (Exception ex)
            {
                ajaxResult.Result = AjaxResult.VALUE_ERROR;
                ajaxResult.ErrMesgs = new string[]{
                    string.Format("{0} = {1}", ex.GetType().FullName, ex.Message)
                };
            }
            return Json(ajaxResult);
        }
        #endregion

ConvertViewToString ini akan melakukan mengirim data terlebih dahulu ke file cshtml setelah itu hasilnya diubah menjadi sebuah string dan ditampung oleh parameter ViewHtml.


private string ConvertViewToString(string viewName, object model)
        {
            ViewData.Model = model;
            using (StringWriter writer = new StringWriter())
            {
                ViewEngineResult vResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext vContext = new ViewContext(this.ControllerContext, vResult.View, ViewData, new TempDataDictionary(), writer);
                vResult.View.Render(vContext, writer);
                return writer.ToString();
            }
        }

Script:

function myFunction(){
 function onSearchCriteria2(page) {
            var params = new Object();
            var data = new Object();

            params.recordPerPage = 100;
            params.currentPage = page;
            params.data = data;
            data.Name = $("#Name").val();
            data.Gender = $("#Gender").val();
            data.Email = $("#Email").val();
            data.ClassM = $("#ClassM").val();

            $.ajax({
                type: "POST",
                contentType: 'application/json',
                url: "@Url.Content("~/QCGate/GetByKeyPaging")",
                data: JSON.stringify(params),
                success: function (returnResult) {
                    //console.log(returnResult.ViewHtml);

                    if (returnResult.Result == 'SUCCESS') {
                        $("#divGrid").html(returnResult.ViewHtml);
                    }
                },
                error: function (data) {
                    popUpProgressHide();
                }
            });
        }
Share This :

0 Comments