ControllerContext and ViewData External controller scope - MVC3 C #

I process PartialViews / Models using the method below to send template letters.

I am using the code below to convert the partial and model to an html string that I can pass into the email sending code.

public class BaseController : Controller
{
    public string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            throw new ArgumentException("No View Path Provided.");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}

This currently works in BaseController, I would like to move it to a helper method so that I can move my email model by building / unloading the controller.

The problem is that I do not have access to ViewData / TempData / ControllerContext

I can update the ControllerContext, but I do not know what to do with ViewData / TempData.

This is how I will use what I have in the controller:

//Do Stuff in Controller

var html = RenderPartialViewToString("~/Views/Mail/_ForgotPassword.cshtml", new MailModel { Username = "Skrillex", SomethingElse = "foo" });

//Send the Email
+5
source share
3

, , , .

Razor HTML- . . , - , .

, ( ):

  • Razor
  • , ,
  • , Render
  • . , , .

, , , .

, , , .

+2

BaseController , ,

public sealed class Helper {
///Gets or sets BaseController
public BaseController { get; set; }
#region "Constructors"
/// <summary>
/// Initialises a new instance of the <see cref="Helper" /> class.
/// </summary>
public Helper() : base() {

}
/// <summary>
/// Initialises a new instance of the <see cref="Helper" /> class.
/// </summary>
public Helper(BaseController baseController) : this() {
   this.BaseController = baseController;
}
#endregion
public void SendEmail(){
   // Here you can call your RenderPartialViewToString from the BaseController
 var m_RenderPartialViewToString = this.BaseController.RenderPartialViewToString( .......);
}}

. , .

0

I used 2 methods for Razor rendering that need to be sent to the controller side ... first I transferred the ControllerContext to my service level, which worked as expected, but not perfect ... Often my services are used by command-line applications or compiled into a Windows service, where there is no ControllerContext available ... During my second attempt, I used this Razor rendering engine: http://razorengine.codeplex.com/ or https://github.com/Antaris/RazorEngine

0
source

All Articles