渲染字符串为razor cshtml

时间:2012-02-24 12:21:50

标签: asp.net-mvc-3 razor

public ActionResult Index()
{
    return View("ViewName");  // cshtml file name
}

这通常有效。

public ActionResult Index()
{
    string razor = "<p>Date: @DateTime.Now</p>";
    return View(razor);
}

我能做那样的事吗?不渲染.cshtml文件,渲染字符串......

- 编辑------

我实际上是以编程方式创建.cshtml文件。例如,我将在我的字符串中使用@ Html.TextBoxFor(...)或foreach语句。 - 刚刚编辑E-D

3 个答案:

答案 0 :(得分:1)

这是否回答了你的问题:

动作:

public ActionResult Index()
{
    HtmlString razor = new HtmlString(string.Format("<p>Date: {0}</p>", DateTime.Now.ToString()));
    return View(razor);
}

查看Index.cshtml:

@model HtmlString

@Model

解决方案2,在Controller中实现,不需要视图:

public HtmlString Index()
{
    return new HtmlString("<p>Hello World!</p>");
}

答案 1 :(得分:0)

尝试使用ContentResult

return Content(String.Format("<p>Date: {0}</p>",DateTime.Now));

答案 2 :(得分:0)

RazorEngine完全解决了我的问题。谢谢大家。 http://razorengine.codeplex.com/

相关问题