심재운 블로그


DisplayMutiplePartialView.zip




base Controller 를 생성해 보자.

여기에는 JSON 을 사용하는지에 대한 여부를 기술한 부분이다.


    public class BaseController : Controller
    {
        protected internal virtual CustomJsonResult CustomJson(object json = null, bool allowGet = true)
        {
            return new CustomJsonResult(json)
            {
                JsonRequestBehavior = allowGet ? JsonRequestBehavior.AllowGet : JsonRequestBehavior.DenyGet
            };
        }
    }

    public class CustomJsonResult : JsonResult
    {
        public CustomJsonResult(object json)
        {
            _json = json;
            _partials = new List<KeyValuePair<string, object>>();
            _results = new List<string>();
        }

        private readonly object _json;
        private readonly IList<KeyValuePair<string, object>> _partials;
        private readonly IList<string> _results;

        public CustomJsonResult AddPartialView(string partialViewName = null, object model = null)
        {
            _partials.Add(new KeyValuePair<string, object>(partialViewName, model));
            return this;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            foreach (var partial in _partials)
            {
                var html = ControllerHelper.RenderPartialViewToString(context, partial.Key, partial.Value);
                _results.Add(html);
            }
            base.Data = Data;
            base.ExecuteResult(context);
        }

        public new object Data
        {
            get
            {
                return new
                {
                    Html = _results,
                    Json = _json
                };
            }
        }
    }


ControllerHelper 클래스를 구현해 보자.이는 partial view  의 내용을 문자열 형태로 변환해 주는 역할을 합니다.



    public static class ControllerHelper
    {
        public static string RenderPartialViewToString(ControllerContext context, string viewName, object model)
        {
            var controller = context.Controller;

            var partialView = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);

            var stringBuilder = new StringBuilder();
            using (var stringWriter = new StringWriter(stringBuilder))
            {
                using (var htmlWriter = new HtmlTextWriter(stringWriter))
                {
                    controller.ViewData.Model = model;
                    partialView.View.Render(
                        new ViewContext(
                            controller.ControllerContext,
                            partialView.View,
                            controller.ViewData,
                            new TempDataDictionary(),
                            htmlWriter),
                        htmlWriter);
                }
            }
            return stringBuilder.ToString();
        }
    }


이제 2개의 partial views 를 추가할 것입니다.


        public JsonResult CreatePartialView()
        {
            MyMultipleUpdateViewModel obj = new MyMultipleUpdateViewModel();
            obj.myTest1ViewModel = new MyTest1ViewModel();
            obj.myTest1ViewModel.MyTestUpdate = "Test1s " + DateTime.Now.ToString();

            obj.myTest2ViewModel = new MyTest2ViewModel();
            obj.myTest2ViewModel.MyTestUpdate = "Test2s " + DateTime.Now.ToString();
            var json = new { Header = "Headers", Footer = "Footers" };
            return CustomJson(json).AddPartialView("_MyTest1PartialView", obj)
                .AddPartialView("_MyTest2PartialView", obj);
        }

참고로 model 정보는 아래와 같습니다.


namespace DropdownGrid.Models
{
    public class MyTest1ViewModel
    {
        public string MyTestUpdate;
    }
    public class MyTest2ViewModel
    {
        public string MyTestUpdate;
    }
    public class MyMultipleUpdateViewModel
    {
        public MyTest1ViewModel myTest1ViewModel;

        public MyTest2ViewModel myTest2ViewModel;
    }
}


아래 사진은 부분 뷰 위치를 알려드립니다.



@model DropdownGrid.Models.MyMultipleUpdateViewModel

@{
    ViewBag.Title = "Display Mutiple Partial View Demo";
}

<h2>Index</h2>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.10.2.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>


<script>
    function GetData(url, onSuccess) {
        
        $.ajax({
            type: "GET",
            cache: false,
            url: url,
            dataType: "json",
            success: function (data, textStatus, jqxhr) {
                onSuccess(data.Json, data.Html);
            },
            error: function (data, text, error) {
                alert("Error: " + error);
            }
        });
        return false;
    }
    function UpdateDiv(json, html) {        
        $("#PartialViewDiv1").html(html[0]);
        $("#PartialViewDiv2").html(html[1]);        
    }
</script>

<input type="button" onclick="GetData('/DisplayMutiplePartialView/CreatePartialView', UpdateDiv);" value="Display Multiple Partial View" />
<br>
<br>
     <div id="PartialViewDiv1"></div>
<br>
<br>
 <div id="PartialViewDiv2"></div>
<br>
<br>




이 글을 공유합시다

facebook twitter kakaoTalk kakaostory naver band

본문과 관련 있는 내용으로 댓글을 남겨주시면 감사하겠습니다.

비밀글모드