How to get partialview string in apicontroller in mvc

I have an apicontroller like this:

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

}

      

I have a partial view say "menu.cshtml", I want to use this partial view and give the menu in line. I have tried various functions that say renderpartialviewtostring, but they use the controller in it, but I use ApiController

Please, help

+3


source to share


1 answer


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

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

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

In your case, you can create a StringActionResult derived from IHttpActionResult which does something similar 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});

        }

    }

      

0


source







All Articles