Click here to Skip to main content
Click here to Skip to main content
Articles » Web Development » ASP.NET » General » Downloads
 
Add your own
alternative version

Partial Rendering Control using JQuery in MVC 2

, 13 Jun 2010
This article shows a web custom control that allows partial rendering using JQuery in an MVC 2 web application
JqueryControlMVC.zip
JqueryController
bin
Debug
JqueryController.dll
MvcApplication2.dll
MvcApplication2.pdb
Release
System.Web.Mvc.dll
JqueryController.csproj.user
Properties
JqueryControlMVC
JqueryControlMVC
App_Data
bin
JqueryController.dll
JqueryController.pdb
JqueryControlMVC.dll
JqueryControlMVC.pdb
Content
Controllers
Global.asax
JqueryControlMVC.csproj.user
Models
Properties
Scripts
Views
Account
Home
Shared
UserControl
JqueryControlMVC.suo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.IO;

namespace JqueryController
{
    

   public class MvcControllerBase : Controller
    {

        private bool _IsPartialRendering = false;
        private StringBuilder _ResponseToRender = new StringBuilder();
        private Dictionary<string, string> _postParameters = new Dictionary<string, string>();
        private string strParameters = string.Empty;
        public MvcControllerBase() { }


        public Dictionary<string, string> PostParameter {
            get { return _postParameters; }
        }

        public StringBuilder ResponseToRender
        {
            get
            {
                return _ResponseToRender;
            }
        }

        public bool IsPartialRendering
        {
            get
            {
                return _IsPartialRendering;
            }
            set
            {
                _IsPartialRendering = value;
            }
        }

        public bool PanelRefresh { get; set; }


      
        private void PopulatePostParameters(string strParams)
        {
            try
            {

                string[] parameters = strParams.Split('&');
                for (int i = 0; i < parameters.Length; i++)
                {
                    if (string.IsNullOrEmpty(parameters[i]) == false)
                    {
                        int equalPosition = parameters[i].IndexOf("=");
                        this._postParameters.Add(parameters[i].Substring(0, equalPosition), parameters[i].Substring(equalPosition + 1));
                    }
                }
            }
            catch (Exception ex)
            {
                throw new FormatException("The parameters string is not in the correct format", ex);
            }


        }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
        }

        protected override void  OnActionExecuting(ActionExecutingContext filterContext)
        {

            IsPartialRendering = false;
            if (filterContext.HttpContext.Request.Form["__parameters"] != null)
            {
                IsPartialRendering = true;
                this.PopulatePostParameters(filterContext.HttpContext.Request.Form["__parameters"]);
            }           
            base.OnActionExecuting(filterContext);
       }

        public ActionResult RefreshJQueryPanel<T>(string JQueryPanelId, string UserViewControlPath, T model)
        {
            const string PREFIX = @"$(""[id$='_";
            const string SUFFIX = @"']"")";
            string Html = string.Empty;
            var vd = new ViewDataDictionary(this.ViewData);
            var vp = new ViewPage
            {
                ViewData = vd,
                ViewContext = new ViewContext(),
                Url = new UrlHelper(this.ControllerContext.RequestContext)
            };
            vp.ViewData.Model = model;
            ViewUserControl v = (ViewUserControl)vp.LoadControl(UserViewControlPath);
            vp.Controls.Add(v);
            var sb = new StringBuilder();
            using (var sw = new StringWriter(sb))
            {
                using (var tw = new HtmlTextWriter(sw))
                {
                    vp.RenderControl(tw);
                }
            }
            Html = sb.ToString();
            Html = Html.Replace("\\", "\\\\");
            Html = Html.Replace(Environment.NewLine, string.Empty);
            Html = Html.Replace(@"""", "\\\"");
            
            return this.Content(PREFIX + JQueryPanelId + SUFFIX + @".html(""" + Html + @""");");
        }



        public ActionResult RefreshJQueryPanel<T>(string JQueryPanelId, string UserViewControlPath, T model, string functionName, params string[] callBackParms)
        {
            const string PREFIX = @"$(""[id$='_";
            string SUFFIX = @"']"")";
            string Html = string.Empty;
             var sb = new StringBuilder();
            var vd = new ViewDataDictionary(this.ViewData);
            var vp = new ViewPage
            {
                ViewData = vd,
                ViewContext = new ViewContext(),
                Url = new UrlHelper(this.ControllerContext.RequestContext)
            };
            vp.ViewData.Model = model;
            ViewUserControl v = (ViewUserControl)vp.LoadControl(UserViewControlPath);
            vp.Controls.Add(v);
           
            using (var sw = new StringWriter(sb))
            {
                using (var tw = new HtmlTextWriter(sw))
                {
                    vp.RenderControl(tw);
                }
            }
            Html = sb.ToString();         
            Html = Html.Replace("\\", "\\\\");
            Html = Html.Replace(Environment.NewLine, string.Empty);
            Html = Html.Replace(@"""", "\\\"");
            return this.Content(PREFIX + JQueryPanelId + SUFFIX + @".html(""" + Html + @""");" + AddCallBack(functionName, callBackParms));
        }


        private string AddCallBack(string functionName, params string[] callBackParms)
        {
            StringBuilder ParamToJs = new StringBuilder();
            if (callBackParms.Length > 0)
            {
                foreach (string parm in callBackParms)
                {
                    ParamToJs.Append("'" + parm + "',");
                }
                ParamToJs.Remove(ParamToJs.Length - 1, 1);
            }
            return functionName + "(" + ParamToJs.ToString() + ");";           
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Massimiliano Peluso "WeDev Limited"
Architect PeluSoft Limited
United Kingdom United Kingdom
I have been fascinated by software development since I was 10 years old. I'm proud of learned the first programming language with an Olivetti PC 128S based on Microsoft BASIC. I'm a Software Architect/Senior Developer with a strong background of all the developing Microsoft's technologies.

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 14 Jun 2010
Article Copyright 2010 by Massimiliano Peluso "WeDev Limited"
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid