【发布时间】:2010-10-07 22:11:21
【问题描述】:
在我的 AJAX 调用中,我想将一个字符串值返回给调用页面。
我应该使用ActionResult 还是只返回一个字符串?
【问题讨论】:
-
检查 here 以返回引导警报消息
标签: asp.net-mvc ajax actionresult
在我的 AJAX 调用中,我想将一个字符串值返回给调用页面。
我应该使用ActionResult 还是只返回一个字符串?
【问题讨论】:
标签: asp.net-mvc ajax actionresult
您可以只使用ContentResult 来返回一个纯字符串:
public ActionResult Temp() {
return Content("Hi there!");
}
ContentResult 默认返回一个text/plain 作为它的contentType。这是可重载的,所以你也可以这样做:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
【讨论】:
ContentResult 在设置HttpContext.Response.ContentType 之前会执行if (!String.IsNullOrEmpty(ContentType))。我在您的第一个示例中看到text/html,要么这是现在的默认设置,要么是HttpContext 的有根据的猜测。
MediaTypeNames.Text.Plain 或 MediaTypeNames.Text.Xml,而不是直接添加“text/plain”作为字符串。虽然它只包括一些最常用的 MIME 类型。 (docs.microsoft.com/en-us/dotnet/api/…)
如果您知道这是该方法唯一会返回的内容,您也可以只返回字符串。例如:
public string MyActionName() {
return "Hi there!";
}
【讨论】:
return语句用于根据条件发送string或JSON或View,那么我们必须使用Content返回字符串。
public ActionResult GetAjaxValue()
{
return Content("string value");
}
【讨论】:
截至2020年,使用ContentResult仍然是建议above的正确方法,但用法如下:
return new System.Web.Mvc.ContentResult
{
Content = "Hi there! ☺",
ContentType = "text/plain; charset=utf-8"
}
【讨论】:
有两种方法可以将字符串从控制器返回到视图:
第一
您可以只返回字符串,但它不会包含在您的 .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);
}
}
在视图文件中运行AutoProperty,它会将你重定向到Result视图并发送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 运行它。
【讨论】:
public JsonResult GetAjaxValue()
{
return Json("string value", JsonRequetBehaviour.Allowget);
}
【讨论】: