eth0
eth0

Reputation: 5137

Reading Razor View Variables Programmatically

I have "widgets" contained within partial views and iterate over these files to build an available widget list. Within these views there are two variables

@{ ViewBag.Name = "Test Widget"; }
@{ ViewBag.Description = "This is a test widget"; }

self explanatory. Is there a way using RazorEngine (or any other way) to "read" these variables out so I can show the value of ViewBag.Description in my widget list?

Thanks.

Upvotes: 2

Views: 551

Answers (2)

Paul Tyng
Paul Tyng

Reputation: 7584

You can use the RazorGenerator to actually compile the views, then do a sample execution of them to be able to read the data.

See this article on unit testing the razor views, a similar thing may work for you:

http://blog.davidebbo.com/2011/06/unit-test-your-mvc-views-using-razor.html

var view = new Index();

// Set up the data that needs to be accessed by the view
view.ViewBag.Message = "Testing";

// Render it in an HtmlAgilityPack HtmlDocument. Note that
// you can pass a 'model' object here if your view needs one.
// Generally, what you do here is similar to how a controller
//action sets up data for its view.
HtmlDocument doc = view.RenderAsHtml();

//recall name and description
var name = view.ViewBag.Name;
var description = view.ViewBag.Description;

Here is some additional info on the Razor Generator from Phil Haack: http://haacked.com/archive/2011/08/01/text-templating-using-razor-the-easy-way.aspx

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

RazorEngine with a custom base view could be used for this purpose:

public class MyViewModel
{
    public string Name { get; set; }
    public string Description { get; set; }
}

class Program
{
    static void Main()
    {
        // don't ask me about this line :-)
        // it's used to ensure that the Microsoft.CSharp assembly is loaded
        bool loaded = typeof(Binder).Assembly != null;

        Razor.SetTemplateBase(typeof(FooTemplateBase<>));
        string template = 
@"@{ ViewBag.Name = ""Test Widget""; }
@{ ViewBag.Description = ""This is a test widget""; }";
        var model = new MyViewModel();
        var result = Razor.Parse(template, model);
        Console.WriteLine(model.Name);
        Console.WriteLine(model.Description);
    }
}

namespace System.Web.Mvc
{
    public abstract class FooTemplateBase<T> : TemplateBase<T>
    {
        public dynamic ViewBag
        {
            get
            {
                return Model;
            }
        }
    }
}

Upvotes: 1

Related Questions