Getting HTML Rendered by a View in MVC3 - asp.net-mvc-3

In my MVC3 app, I'm testing stuff by creating a new controller and invoking methods like Index(), and storing the resulting ViewResult into a variable called result.
How can I poke this object (or something else) to get the actual HTML returned to the browser?
I am surprised that result.ViewName is empty, result.Model is null, result.View is null, and even result.TempData is empty. (result.ViewBag has stuff I put in the viewbag, so I know the whole stack is working properly.)
If it matters, I'm using the Visual Studio testing, along with NHibernate/ActiveRecord for my stack. But all that is initializing correctly in my test project. (I can get data from entities/objects.)

Things to notice:
1. ViewName is empty if you just write return View(); and don't write the view name explicity.
2. TempData is property of the controller so as for ViewBag. See MSDN
Update: By the way there is a wonderfull library for testing in mvc MvcContrib

This is something that I use to create HTML emails, but could possibly be used in your case as well, outputs the HTML of a view result into a string.
public static string RenderViewToString(Controller controller, string viewName, object model)
{
controller.ViewData.Model = model;
try
{
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, null);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
return sw.ToString();
}
}
catch (Exception ex)
{
return ex.ToString();
}
}

Related

Model is null on postback in ajax loaded partial view

I'm using the following pattern https://github.com/filamentgroup/Ajax-Include-Pattern
to load partial views through ajax.
View:
#using(Html.BeginUmbracoForm("PostContactInformation", "JoiningSurface", null, new Dictionary<string, object> { { "class", "joinform" } })) {
#Html.AntiForgeryToken()
<div data-append="#Url.Action("RenderJoiningContactInformation", "JoiningSurface", new { ContentId = CurrentPage.Id })"></div>
}
With Action:
public ActionResult RenderContactInformation(int ContentId)
{
var viewModel = ContactViewModel();
viewModel.Content = Umbraco.TypedContent(ContentId);
return PartialView("RenderContactInformation", viewModel);
}
Loads partial view perfectly.
// No need to add partial view i think
Post action works correctly as well:
public ActionResult PostContactInformation(ContactViewModel model)
{
//code here
return RedirectToUmbracoPage(pageid);
}
The problem is, that i need to add model error to CurrentUmbracoPage if it exists in post...
For example:
public ActionResult PostContactInformation(ContactViewModel model)
{
ModelState.AddModelError(string.Empty, "Error occurred");
return CurrentUmbracoPage();
}
In this case i get null values for current model. And this happens only when i use ajax.
If i load action synchronously like that:
#using(Html.BeginUmbracoForm("PostJoiningContactInformation", "JoiningSurface", null, new Dictionary<string, object> { { "class", "joinform" } })) {
#Html.AntiForgeryToken()
#Html.Action("RenderContactInformation", "JoiningSurface", new { ContentId = CurrentPage.Id })
}
everything works like it should.
But i need to use ajax. Is there a correct way to pass values on postback in this case? I know that i can use TempData, but i'm not sure that this is the best approach.
Thanks for your patience
The problem is that Umbraco context is not accessible when you're trying to reach it through ajax call. Those calls are a little bit different.
Check my answer in this thread: Umbraco route definition-ajax form and I suggest to go with WebAPI and UmbracoApiControllers to be able to access those values during the Ajax call.

how to iterate ViewBag or how can I copy the values of viewBag from one Action to another Action

I have a base Controller like follow
public abstract class BaseController
{
protected ActionResult LogOn(LogOnViewModel viewModel)
{
SaveTestCookie();
var returnUrl = "";
if (HttpContext != null && HttpContext.Request != null && HttpContext.Request.UrlReferrer != null)
{
returnUrl = HttpContext.Request.UrlReferrer.LocalPath;
}
TempData["LogOnViewModel"] = viewModel;
return RedirectToAction("ProceedLogOn", new { returnUrl });
}
public ActionResult ProceedLogOn(string returnUrl)
{
if (CookiesEnabled() == false)
{
return RedirectToAction("logon", "Account", new { area = "", returnUrl, actionType, cookiesEnabled = false });
}
var viewModel = TempData["LogOnViewModel"] as LogOnViewModel;
if (viewModel == null)
{
throw new NullReferenceException("LogOnViewModel is not found in tempdata");
}
//Do something
//the problem is I missed the values which are set in the ViewBag
}
}
and another Controller
public class MyController : BaseController
{
[HttpPost]
public ActionResult LogOn(LogOnViewModel viewModel)
{
// base.LogOn is used in differnet controller so I saved some details in view bag
ViewBag.Action = "LogonFromToolbar";
ViewBag.ExtraData = "extra data related only for this action";
return base.LogOn(viewModel);
}
}
the problem is I missed the view bag values in ProceedLogOn action method.
I have the values in Logon method in BaseController.
How can I copy the values of ViewBag from one Action to another Action?
So I can not simply say this.ViewBag=ViewBag;
because ViewBag doesn't have setter. I was thinking of Iterating through viewbag.
I tried ViewBag.GetType().GetFields() and ViewBag.GetType().GetProperties() but they return nothing.
ViewData reflects ViewBag
You can iterate the values you've stored like this :
ViewBag.Message = "Welcome to ASP.NET MVC!";
ViewBag.Answer = 42;
foreach (KeyValuePair<string, object> item in ViewData)
{
// if (item.Key = "Answer") ...
}
This link should also be useful
I'm afraid I don't have the answer how to copy ViewBag.
However, I would never use ViewBag that way.
ViewBag is some data the Controller gives to the View to render output if someone does not like to use ViewModel for some reasons. The View should never know anything about the Controller but your ViewBag is holding a ActionName ;).
Anyway, the ProceedLogOn action method has pretty much parameters which is ... not a nice code actually so why hesitate to add more parameters which are currently being hold in MyController.Logon ViewBag? Then inside method ProceedLogOn you have what you want.
;)

Rendering a partial view to a string by calling an action method

I have been experimenting with rendering an view to a string using methods outlines here:
Render a view as a string
The issue is that I need to call my controller action which does not happen when calling View.Render.
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
viewResult.View.Render(viewContext, sw);
My question is, how can I call RenderAction on an arbitrary controller passing in a route? I am trying to composite together the results of a number of partial views into a single result which will get passed back to the browser.
My code so far. Works except that the action method is not called.
public static string RenderPartialViewToString(this Controller controller, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
var route = new RouteData();
route.Values.Add("controller", "Test1");
route.Values.Add("action", "Index");
var controller1 = new Test1Controller();
var controllerContext = new ControllerContext(new RequestContext(this.ControllerContext.HttpContext, route), controller1);
controller1.ControllerContext = controllerContext;
var viewString = controller1.RenderPartialViewToString("~/Views/Test1/Index.cshtml", (object)model);
My goal is to create a simple CMS system that composites together the results of a number of controller actions/views and outputs them into a layout.
I have a primary controller action that retrieves a page description from the database. The code loops over a list of other controllers and calls their actions which results in a dynamic object model and a list of partial html snippets that is handed off to a custom WebViewPage.
I'm somewhat unsure of what you're trying to accomplish. However, that aside RenderPartialViewToString is an extension method. To use within a controller action you could do something as simple as this:
var result = this.RenderPartialViewToString("Index", model)
Where model is the strongly typed model used within the "Index" view. If for example you were wanting to render a view to string to use within a JSON action you could return a JSONResult with:
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new {html = this.RenderPartialViewToString("Index", model)}
};

Return an other action result as string

In my MVC website, I am creating a small forum. For a single post I am rendering my "Single(Post post)" action in my "PostController" like below
<% Html.RenderAction<PostController>(p => p.Single(comment)); %>
Also When a user reply a post I am sending reply as an ajax request to my "CreatePost" action then return "Single" view as result of this action like below
public ActionResult CreatePostForForum(Post post)
{
//Saving post to DB
return View("Single", postViewData);
}
When I do like that only the view is being rendered, Codes in "Single" Actions body isn't beig executed.
What is the best way to do this?
Also I want to return "Single" action result as string in my JsonObject like below
return Json(new{IsSuccess = true; Content= /*HERE I NEED Single actions result*/});
You can use something like this, but be very careful with this. It can actually cause badly traceable errors (for example when you forget to explicitly set view name in Single method).
public ActionResult Single(PostModel model) {
// it is important to explicitly define which view we should use
return View("Single", model);
}
public ActionResult Create(PostModel model) {
// .. save to database ..
return Single(model);
}
Cleaner solution would be to do the same as if it was post from standard form - redirect (XMLHttpRequest will follow it)
For returning ajax views wrapped in json I use following class
public class AjaxViewResult : ViewResult
{
public AjaxViewResult()
{
}
public override void ExecuteResult(ControllerContext context)
{
if (!context.HttpContext.Request.IsAjaxRequest())
{
base.ExecuteResult(context);
return;
}
var response = context.HttpContext.Response;
response.ContentType = "application/json";
using (var writer = new StringWriter())
{
var oldWriter = response.Output;
response.Output = writer;
try
{
base.ExecuteResult(context);
}
finally
{
response.Output = oldWriter;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(serializer.Serialize(new
{
action = "replace",
html = writer.ToString()
}));
}
}
}
It is probably not the best solution, but it works quite well. Note that you will need to manually set View, ViewData.Model, ViewData, MasterName and TempData properties.
My recommendation:
Post your forum reply (and whatever options) via Ajax.
Return your JSONResult, using this method: ASP MVC View Content as JSON to render your content.
In the OnSuccess handler of your ajax call, check if IsSuccess is true. If successful, append the content to the appropriate container using JQuery

Displaying modelstate error

I am having the following code, However the errors causght not being displayed. What is wrong ?
public ActionResult DeleteRateGroup(int id)
{
try
{
RateGroup.Load(id).Delete();
RateGroupListModel list = new RateGroupListModel();
return GetIndexView(list);
}
catch (Exception e)
{
RateGroupListModel model = new RateGroupListModel();
if (e.InnerException != null)
{
if (e.InnerException.Message.Contains("REFERENCE constraint"))
ModelState.AddModelError("Error", "The user has related information and cannot be deleted.");
}
else
{
ModelState.AddModelError("Error", e.Message);
}
return RedirectToAction("RateGroup", model);
}
}
#model MvcUI.Models.RateGroupListModel
#{
View.Title = "RateGroup";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Rate Group</h2>
#Html.ValidationSummary()
#using (Html.BeginForm())
private ActionResult GetIndexView(RateGroupListModel model)
{
return View("RateGroup", model);
}
public ActionResult RateGroup(RateGroupListModel model)
{
return GetIndexView(model);
}
It looks like you're setting the ModelState error, then redirecting to another action. I'm pretty sure the ModelState gets lost when you do that.
Typically, you'd just render the RateGroup view directly from the DeleteRateGroup action, without the redirect, passing in your model if needed, like this:
return View("RateGroup", model);
If you want the ModelState to come along to the second action with you, take a look at MvcContrib's ModelStateToTempDataAttribute. Here's the attribute's description, from the MvcContrib source code's comments:
When a RedirectToRouteResult is returned from an action, anything in the ViewData.ModelState dictionary will be copied into TempData. When a ViewResultBase is returned from an action, any ModelState entries that were previously copied to TempData will be copied back to the ModelState dictionary.

Resources