在ASP.NET MVC中,Response.Write是什么?

4

这很简单,但是

在asp net MVC中,特别是mvc5中,使用经典的webforms "response.write"的最佳方法是什么?

比如说:我只想从控制器向屏幕输出一个简单的字符串。

在mvc中是否存在response.write?

谢谢。


2
你可以从控制器操作中返回一个简单的字符串。 - Hans Kesting
2个回答

11

如果你的方法的返回类型是 ActionResult,那么你可以使用 Content 方法返回任何类型的内容。

public ActionResult MyCustomString()
{
   return Content("YourStringHere");
}

或只需

public String MyCustomString()
{
  return "YourStringHere";
}

Content 方法允许您返回其他内容类型,只需将内容类型作为第二个参数传递即可。

 return Content("<root>Item</root>","application/xml");

4

正如@Shyju所说,您应该使用Content方法。但还有另一种方法,即创建自定义行动结果。您的自定义行动结果可能如下所示:

public class MyActionResult : ActionResult
{
    private readonly string _content;

    public MyActionResult(string content)
    {
        _content = content;
    }
    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.Write(_content);
    }
}

然后你可以这样使用它:
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";

        return new MyActionResult("content");
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接