簡體   English   中英

從ASP.NET MVC控制器傳遞HTML到瀏覽器直接鏈接不會呈現HTML標簽

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM