09 Nov 2010 @ 6:21 PM 

Here is a snippet for rendering a partial view to a string. After you make a string from the view, you can pass the html as a json result. This let’s you have more control over the actions you can take in your javascript when you receive your response.

        public string RenderPartialToString(string controlName, ViewDataDictionary viewDataDictionary)
        {
            var viewContext = new ViewContext();
            var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);

            var viewPage = new ViewPage
            {
                ViewData = viewDataDictionary,
                ViewContext = viewContext,
                Url = urlHelper,
            };

            var control = viewPage.LoadControl(controlName);
            viewPage.Controls.Add(control);

            var sb = new StringBuilder();
            using (var sw = new StringWriter(sb))
            using (var tw = new HtmlTextWriter(sw))
            {
                viewPage.RenderControl(tw);
            }

            return sb.ToString();
        }

What’s important here is that I pass in the viewdatadictionary. I do this so that I can build the modelstate before passing it in to be rendered. In my particular use case I already had a form that was rendering a validation summary and I needed to keep this functionality. So I add my model errors to the new view data dictionary, and the erros render on the partial view. I then return a json result with a false success and the rendered html.

Here’s is an example of the controller action.

public ActionResult VerifyThisCode(string code)
        {
            var dataDictionary = new ViewDataDictionary();
            if(!ValidateCode(code, datadictionary))
            {
                        return Json(new { success = "false", view = RenderPartialToString("~/Views/Verify/BadCode.ascx", datadictionary) });
            }
            if(NotLoggedIn())
            {
                        dataDictionary.ModelState.AddModelError("NotLoggedIn", "Please, log in or sign up to redeem this code.");
                        dataDictionary.Model = Request.UrlReferrer.AbsolutePath.ToString();
                        return Json(new { success = "false", view = RenderPartialToString("~/Views/Shared/LoginSignup.ascx", dataDictionary) });
            }
            Code validCode = _codeRepository.GetCode(code);
            dataDictionary.Model = Code;
            return Json(new { success = "true", view = RenderPartialToString("~/Views/Verify/GoodCode.ascx", dataDictionary) });
}

I can change what model I set on the data dictionary depending on which view I want to use. Or set none at all. Now finally the javascript that uses this.

$('#validateCode').click(function(event) {
            event.preventDefault();
            $.ajax({
                url: path + 'Verify/VerifyThisCode',
                data: $('#code').val(),
                success: function(data) {
                    $('#codeContent').html('');
                    $('#codeContent').append(data.view);
                    $('#codeRedeemed').fadeIn();
                    if (data.success == 'true') {
                        RefreshMySelectionOfCodes();
                    }
                }

            });
        });

What this does is show a modal dialog with my partial view rendered into it. But only in the event of a success do I refresh the selection of codes.

Posted By: boyd21
Last Edit: 14 Apr 2011 @ 10:33 PM

EmailPermalink
Tags
Tags: , , ,
Categories: .Net, Programming


 

Responses to this post » (None)

 
Tags
Comment Meta:
RSS Feed for comments

 Last 50 Posts
Change Theme...
  • Users » 3
  • Posts/Pages » 30
  • Comments » 0
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

GeekPub



    No Child Pages.