简体   繁体   English

从ASP.NET MVC控制器传递HTML到浏览器直接链接不会呈现HTML标签

[英]Passing HTML from ASP.NET MVC controller to browser direct link is not rendering HTML tags

My HelloWorldController : 我的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...";
    }
}

Viewing the page on: http://localhost:12121/HelloWorld 查看以下页面: http://localhost:12121/HelloWorld

It returns: 它返回:

This is my <b>default</b> action...

Why does it not render the bold tags? 为什么不呈现粗体标签?

try this : 尝试这个 :

 public ActionResult Index()
 {
     return Content("This is my <b>default</b> action...");
 }

I don't think you should be passing HTML from controller, you should use cshtml views to render HTML, and rendering different things by passing a model to your view by your controller. 我不认为您应该从控制器传递HTML,应该使用cshtml视图来呈现HTML,并通过控制器将模型传递给视图来呈现不同的事物。

Here is an example of controller method : 这是控制器方法的示例:

public ActionResult Index()
{
    MyModel model = new MyModel()
    {
        Text = "Hello world"
    };

    return this.View(model);
}

Here is an example of cshtml view : 这是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

You would need to change the return type to ActionResult and then use Content() and explicitly specify the content type that is being returned so that browser knows it is html and would render it, right know it is returning as Html Encoded string so browser wouldn't render it: 您将需要将返回类型更改为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM