3

i have a apicontroller like this:

public class MenuController : ApiController
{
    [HttpGet]
    public string GetMenu([FromUri]string page, [FromUri]string menu)
    {
    }

}

I have a partialview say "menu.cshtml" i want to use that partialview and give the menu in string . I have tried various functions that says renderpartialviewtostring but they use controller in it but i am using ApiController

Please help

tereško
  • 58,060
  • 25
  • 98
  • 150
Rusty
  • 1,303
  • 2
  • 14
  • 28

1 Answers1

0

You can derive your own type from IHttpActionResult and do it.

This article speaks about it - http://www.strathweb.com/2013/06/ihttpactionresult-new-way-of-creating-responses-in-asp-net-web-api-2/

You will need a reference to RazorEngine - http://www.nuget.org/packages/RazorEngine/

In your case you can create a StringActionResult derived from IHttpActionResult that does something similar to below.

public class StringActionResult : IHttpActionResult
{
    private const string ViewDirectory = @"c:\path-to-views";
    private readonly string _view;
    private readonly dynamic _model;

    public StringActionResult(string viewName, dynamic model)
    {
        _view = LoadView(viewName);
        _model = model;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        var parsedView = RazorEngine.Razor.Parse(_view, _model);
        response.Content = new StringContent(parsedView);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
        return Task.FromResult(response);
    }

    private static string LoadView(string name)
    {
        var view = File.ReadAllText(Path.Combine(ViewDirectory, name + ".cshtml"));
        return view;
    }
}

and then in your controller, do something like this.

  public class MenuController : ApiController
    {
        [HttpGet]
        public StringActionResult GetMenu([FromUri]string page, [FromUri]string menu)
        {
             return new StringActionResult("menu", new {Page: page, Menu: menu});

        }

    }
govin
  • 6,445
  • 5
  • 43
  • 56