Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a View from String

I am experimenting in MVC 4, and i was wandering if it is possible to turn a string into a View and return this from the Controller.

For instance, i have a method that reads the View contents into a string. I would like to process that string before rendering it. So i would like the Controller to output the modified string as a View.

Is this even possible?

Just to make a note, this will happen after Razor has made any changes. I do have a method that gets the final View into a string.

Edit

I have the following method:

    public static string RenderViewToString(this 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();
        }
    }

which returns the finally rendered View (what is actually going to be displayed in the browser) into a string.

I need to do the opposite. Having a string, output a View.

So if i have the following cshtml:

<!doctype html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    Hello World
</body>
</html>

The above function will return a string like:

"<!doctype html><head><title>MyActualTitle</title></head><body>Hello World</body></html>"

Now what i want is take this string, manipulate it and render it. For instance i want to change the Hello World. I know i can do this with Razor, i was just wandering if i can do this with another method.

like image 735
Giannis Paraskevopoulos Avatar asked Oct 07 '13 10:10

Giannis Paraskevopoulos


2 Answers

Yes is possible:

public sealed class StringController : Controller
{
    //
    // GET: /String/
    public string Index()
    {
        return "Hello world!";
    }
}

If you want razor to process it before returning, then I'm not sure how to do that, but you probably don't need to go via a View to do that.

like image 176
weston Avatar answered Sep 20 '22 07:09

weston


If you need to create a view form string .Then see this discussions

Render a view as a string

ASP.NET MVC3 Razor - create view from a string?

like image 29
Ramesh Rajendran Avatar answered Sep 20 '22 07:09

Ramesh Rajendran