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

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

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

351029 次浏览

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

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

ContentResult默认返回text/plain作为其属性类型。这是可重载的,因此您还可以执行以下操作:

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

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

public string MyActionName() {
return "Hi there!";
}
public ActionResult GetAjaxValue()
{
return Content("string value");
}
public JsonResult GetAjaxValue()
{
return Json("string value", JsonRequetBehaviour.Allowget);
}

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

第一

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


第二

您可以返回一个字符串作为View Result的Model对象。

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

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);


}
}

在运行自动产权的视图文件中,它会将您重定向到结果视图并将发送<的trong>的
代码到视图

<!--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年,使用ContentResult仍然是建议上面的正确方法,但用法如下:

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

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

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

这通常能奏效