[英]Passing HTML from ASP.NET MVC controller to browser direct link is not rendering HTML tags
我的HelloWorldController
:
public class HelloWorldController : Controller
{
// GET: /HelloWorld/
public string Index() {
return "This is my <b>default</b> action...";
}
// GET: /HelloWorld/Welcome/
public string Welcome() {
return "This is the Welcome action method...";
}
}
查看以下页面: http://localhost:12121/HelloWorld
它返回:
This is my <b>default</b> action...
为什么不呈现粗体标签?
尝试这个 :
public ActionResult Index()
{
return Content("This is my <b>default</b> action...");
}
我不认为您应该从控制器传递HTML,应该使用cshtml视图来呈现HTML,并通过控制器将模型传递给视图来呈现不同的事物。
这是控制器方法的示例:
public ActionResult Index()
{
MyModel model = new MyModel()
{
Text = "Hello world"
};
return this.View(model);
}
这是cshtml视图的示例:
@* This is the model you passed, you must pass the correct path to it's class *@
@model MyApp.Models.MyModel
@* This should render the "Hello world" message *@
@Model.Text
您将需要将返回类型更改为ActionResult
,然后使用Content()
并显式指定要返回的内容类型,以便浏览器知道它是html并将呈现它,正确知道它以Html编码字符串的形式返回,因此浏览器不会不渲染它:
public ActionResult Index()
{
return Content("This is my <b>default</b> action...", "text/html");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.