一个Web API控制器可以呈现一个视图作为字符串? [英] Can a Web Api controller render a view as a string?

查看:156
本文介绍了一个Web API控制器可以呈现一个视图作为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个Web API控制器行动,将根据结果发送电子邮件。我想用一个MVC视图或局部视图的数据模型来呈现电子邮件的正文。

I would like to write a Web Api controller action that would send an email depending on results. I would like to use an MVC View or Partial view with a model of data to render the body of the email.

有没有办法做到这一点?

Is there a way to do this?

我想是这样的:

public class NotificationApiController : ApiController
{
    private IMkpContext db;

    public string ViewNotifications()
    {
        var dataModel = GetDataModel();
        if (dataModel != null) 
        {
            SendEmail(dataModel.ToAddress, dataModel.FromAddress, dataModel.Subject, RenderBody("viewName", dataModel);
        }

        return string.Empty;
    }
}

在哪里RenderBody将查找的viewName,从数据模型填充数据,并渲染视图作为一个字符串。

Where RenderBody would look up the viewName, populate it with data from dataModel, and render the View as a string.

推荐答案

如果您不想将去与RazorEngine的做法提出了意见,你可以这样定义一个类:

If you don´t want to go with the RazorEngine approach suggested in the comments, you could define a class like this:

public static class ViewUtil
{
    public static string RenderPartial(string partialName, object model)
    {
        var sw = new StringWriter();
        var httpContext = new HttpContextWrapper(HttpContext.Current);

        // point to an empty controller
        var routeData = new RouteData();
        routeData.Values.Add("controller", "EmptyController");

        var controllerContext = new ControllerContext(new RequestContext(httpContext, routeData), new EmptyController());

        var view = ViewEngines.Engines.FindPartialView(controllerContext, partialName).View;

        view.Render(new ViewContext(controllerContext, view, new ViewDataDictionary { Model = model }, new TempDataDictionary(), sw), sw);

        return sw.ToString();
    }
}

class EmptyController : Controller { }

这篇关于一个Web API控制器可以呈现一个视图作为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆