Asp.net mvc 在MVC中,如何返回字符串结果?

Asp.net mvc 在MVC中,如何返回字符串结果?,asp.net-mvc,ajax,actionresult,Asp.net Mvc,Ajax,Actionresult,在我的AJAX调用中,我希望将字符串值返回到调用页面 我应该使用ActionResult还是只返回一个字符串 只需使用返回普通字符串即可: public ActionResult Temp() { return Content("Hi there!"); } 默认情况下,返回一个text/plain作为其默认值。这是可重载的,因此您还可以执行以下操作: return Content("<xml>This is poorly formatted xml.</xml>

在我的AJAX调用中,我希望将字符串值返回到调用页面

我应该使用
ActionResult
还是只返回一个字符串

只需使用返回普通字符串即可:

public ActionResult Temp() {
    return Content("Hi there!");
}
默认情况下,返回一个
text/plain
作为其默认值。这是可重载的,因此您还可以执行以下操作:

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
返回内容(“这是格式不好的xml。”,“text/xml”);

如果知道字符串是该方法唯一会返回的内容,也可以只返回字符串。例如:

public string MyActionName() {
  return "Hi there!";
}

有两种方法可以将字符串从控制器返回到视图:

首先

您可以只返回字符串,但它不会包含在.cshtml文件中。它将只是一个字符串出现在您的浏览器中。


您可以返回一个字符串作为视图结果的模型对象

下面是执行此操作的代码示例:

public class HomeController : Controller
{
    // GET: Home
    // this will return just a string, not html
    public string index()
    {
        return "URL to show";
    }

    public ViewResult AutoProperty()
    {   
        string s = "this is a string ";
        // name of view , object you will pass
        return View("Result", s);

    }
}
在要运行的视图文件中,它会将您重定向到结果视图,并发送s
将代码添加到视图中

<!--this will make this file accept string as it's model-->
@model string

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Result</title>
</head>
<body>
    <!--this will represent the string -->
    @Model
</body>
</html>

@模型串
@{
布局=空;
}
结果
@模型
我在http://localhost:60227/Home/AutoProperty.

截至2020年,使用仍然是建议的正确方法,但使用情况如下:

return new System.Web.Mvc.ContentResult
{
    Content = "Hi there! ☺",
    ContentType = "text/plain; charset=utf-8"
}

Phil,这是“最佳实践”吗?请您解释一下您的答案和@swilliam'之间的区别。您不能从返回ActionResult的方法返回字符串,因此在本例中,您可以按照swilliams的解释返回内容(“”)。如果您只需要返回一个字符串,那么您将让该方法返回一个字符串,正如Phil解释的那样。假设同一个动作有多个
return
语句,用于根据条件发送
string
JSON
View
,那么我们必须使用
Content
返回字符串。如果返回类型是字符串,那么contentType是什么?我不知道这个答案有多准确当时是,但当前
ContentResult
在设置
HttpContext.Response.ContentType
之前,如果(!String.IsNullOrEmpty(ContentType))则执行
操作。我在第一个示例中看到了
text/html
,要么这是默认值,要么这是由
HttpContext
进行的有根据的猜测。我如何访问视图?小的添加:不是直接将“text/plain”添加为字符串,您可以使用.NET framework常量,如
MediaTypeNames.Text.Plain
MediaTypeNames.Text.Xml
。尽管它只包括一些最常用的MIME类型。()投票赞成,但在根据@Stijn comment以文本形式返回HTML时,我确实需要将mime类型指定为“text/plain”。检查以返回引导警报消息在回答时更好地解释更多内容
<!--this will make this file accept string as it's model-->
@model string

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Result</title>
</head>
<body>
    <!--this will represent the string -->
    @Model
</body>
</html>
return new System.Web.Mvc.ContentResult
{
    Content = "Hi there! ☺",
    ContentType = "text/plain; charset=utf-8"
}