C# 将HTML从ASP.NET MVC控制器传递到浏览器直接链接不会呈现HTML标记
MyC# 将HTML从ASP.NET MVC控制器传递到浏览器直接链接不会呈现HTML标记,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,MyHelloWorldController: public class HelloWorldController : Controller { // GET: /HelloWorld/ public string Index() { return "This is my <b>default</b> action..."; } // GET: /HelloWorld/Welcome/ public strin
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...";
}
}
为什么不显示粗体标记?试试以下方法:
public ActionResult Index()
{
return Content("This is my <b>default</b> action...");
}
public ActionResult Index()
{
返回内容(“这是我的默认操作…”);
}
您需要将返回类型更改为ActionResult
,然后使用Content()
并显式指定返回的内容类型,以便浏览器知道它是html并将其呈现,正确地说,它将返回,因为浏览器不会呈现它:
public ActionResult Index()
{
return Content("This is my <b>default</b> action...", "text/html");
}
public ActionResult Index()
{
返回内容(“这是我的默认操作…”,“text/html”);
}
我认为您不应该从控制器传递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
你说你正在把它传递给你的观点。什么观点?没有风景。您只是发送了一个字符串。很抱歉,它只是在页面上显示该字符串-如何强制它按照it呈现的字符串呈现HTML。上述操作应该有效,您是如何调用它的?只需从浏览器中的链接直接到Index()函数以返回字符串您可以尝试以下方法:
public ActionResult Index(){return Content(“这是我的默认操作…”,“text/html”);}
这并没有解决它仍然不会呈现粗体标记的问题。
@* 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