ChatGPT解决这个技术问题 Extra ChatGPT

在 MVC 中,如何返回字符串结果?

在我的 AJAX 调用中,我想将一个字符串值返回给调用页面。

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

选中 here返回引导警报消息

B
Bakudan

您可以只使用 ContentResult 返回纯字符串:

public ActionResult Temp() {
    return Content("Hi there!");
}

默认情况下,ContentResult 返回一个 text/plain 作为其 contentType。这是可重载的,因此您还可以执行以下操作:

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");

如果您的返回类型是字符串,那么 contentType 是什么?
我不知道当时这个答案有多准确,但目前 ContentResult 在设置 HttpContext.Response.ContentType 之前会if (!String.IsNullOrEmpty(ContentType))。我在您的第一个示例中看到了 text/html,要么这是现在的默认设置,要么是 HttpContext 的有根据的猜测。
如何在视图中访问?
小补充:您可以使用像 MediaTypeNames.Text.PlainMediaTypeNames.Text.Xml 这样的 .NET 框架常量,而不是字面上添加“text/plain”作为字符串。虽然它只包括一些最常用的 MIME 类型。 (docs.microsoft.com/en-us/dotnet/api/…)
投了赞成票,尽管在根据@Stijn 评论将 HTML 作为文本返回时,我确实需要将 mime 类型指定为“text/plain”。
H
Haacked

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

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

菲尔,这是一个“最佳实践”吗,你能解释一下你的答案和@swilliam 的区别吗?
您不能从返回 ActionResult 的方法中返回字符串,因此在这种情况下,您会按照 swilliams 的解释返回 Content("")。如果您只需要返回一个字符串,那么您将让该方法返回一个字符串,正如 Phil 解释的那样。
假设同一个动作有多个 return 语句用于根据条件发送 stringJSONView,那么我们必须使用 Content 来返回字符串。
M
Madhav Singh Raghav
public ActionResult GetAjaxValue()
{
   return Content("string value");
}

最好在回答时解释更多
J
Jack Miller

截至 2020 年,使用 ContentResult 仍然是提议的 above 的正确方法,但用法如下:

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

B
Benj Sanders

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

第一的

您可以只返回字符串,但它不会包含在您的 .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);

    }
}

在视图文件中运行 AutoProperty,它会将您重定向到结果视图并将 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 运行它。


N
Naktibalda
public JsonResult GetAjaxValue() 
{
  return Json("string value", JsonRequetBehaviour.Allowget); 
}

W
Walter Verhoeven

您可以只返回一个字符串,但某些 API 不喜欢它,因为响应类型不适合响应,

[Produces("text/plain")]
public string Temp() {
    return Content("Hi there!");
}

这通常可以解决问题