0

I'm using .net MVC 5 to build a web application and trying to implement a method similar to the View() method of the Controller class but only return the evaluated html string.

I have my class Person.cs:

public class Person
{
    public string name {get; set;}
    public string address {get; set;}
}

And my view template PersonSummary.cshtml:

@model Project.Models.Person
<html>
    <h1>Name: @Model.Name</h1>
    <p>Address: @Model.Address</p>
</html>

What I want to do is:

Person person = new Person(){ name = "foo", address = "bar" };
string myHTML = myNewFunction("PersonSummary", person);

I do have a current solution (hack) of creating a seperate controller and getting the string from the ActionResult but after something a little more elegant.

0

1 Answer 1

1

Maybe it's worth trying to use RazorEngine? It's perfect to use for simple views (as your). It fits perfect f.e. for generating html emails.

Sample methods:

public string Compile<T>(string viewContent, T model)
{
    return Razor.Parse(viewContent, model);
}

public string CompileFromPath<T>(string viewPath, T model)
{
    if (!File.FileExists(viewPath))
    {
        return null;
    }

    var viewContent = File.ReadAllText(viewPath, System.Text.Encoding.UTF8);

    return this.Compile(viewContent, model);
}

Usage:

var html = CompileFrompath(Server.MapPath("~/my/view/path.cshtml"), person);

Remarks:

  1. I'm not sure how library handles with iddational helpers for Html or Url. I belive that it can be configured to handle all desired extensions.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I ended up going for the RazorEngine and just using a string as my view. Unfortunately couldn't get the read from file working on the server so I lost intellisense. Will revisit later, Cheers!
@user2865446 feel free to post you problem with reading files on server - we can help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.