Riv*_*ver 73 controller return asp.net-mvc-3
还有其他方法可以从控制器返回原始HTML吗?而不是仅使用viewbag.如下:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.HtmlOutput = "<HTML></HTML>";
return View();
}
}
@{
ViewBag.Title = "Index";
}
@Html.Raw(ViewBag.HtmlOutput)
Run Code Online (Sandbox Code Playgroud)
arc*_*hil 143
这样做没有多大意义,因为View应该生成html,而不是控制器.但无论如何,您可以使用Controller.Content方法,它可以指定结果html,内容类型和编码
public ActionResult Index()
{
return Content("<html></html>");
}
Run Code Online (Sandbox Code Playgroud)
或者你可以使用asp.net-mvc框架内置的技巧 - 直接使动作返回字符串.它会将字符串内容传递到用户的浏览器中.
public string Index()
{
return "<html></html>";
}
Run Code Online (Sandbox Code Playgroud)
实际上,对于除了之外的任何操作结果ActionResult,框架会尝试将其序列化为字符串并写入响应.
尝试返回bootstrap警报消息,这对我有用
return Content("<div class='alert alert-success'><a class='close' data-dismiss='alert'>
×</a><strong style='width:12px'>Thanks!</strong> updated successfully</div>");
Run Code Online (Sandbox Code Playgroud)
注意:不要忘记添加引导css并js在视图页面
希望帮助某人.
对我(ASP.NET Core)有用的是设置返回类型ContentResult,然后将 HMTL 包装到其中并将 ContentType 设置为"text/html; charset=UTF-8"。这很重要,因为否则它不会被解释为 HTML,并且 HTML 语言将显示为文本。
这是示例,是控制器类的一部分:
/// <summary>
/// Startup message displayed in browser.
/// </summary>
/// <returns>HTML result</returns>
[HttpGet]
public ContentResult Get()
{
var result = Content("<html><title>DEMO</title><head><h2>Demo started successfully."
+ "<br/>Use <b><a href=\"http://localhost:5000/swagger\">Swagger</a></b>"
+ " to view API.</h2></head><body/></html>");
result.ContentType = "text/html; charset=UTF-8";
return result;
}
Run Code Online (Sandbox Code Playgroud)