ajax 在MVC中,如何返回一个字符串结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/553936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In MVC, how do I return a string result?
提问by user67033
In my AJAX call, I want to return a string value back to the calling page.
在我的 AJAX 调用中,我想将一个字符串值返回到调用页面。
Should I use ActionResultor just return a string?
我应该使用ActionResult还是只返回一个字符串?
回答by swilliams
You can just use the ContentResultto return a plain string:
您可以只使用ContentResult返回一个普通字符串:
public ActionResult Temp() {
return Content("Hi there!");
}
ContentResultby default returns a text/plainas its contentType. This is overloadable so you can also do:
ContentResult默认情况下返回 atext/plain作为其contentType。这是可重载的,因此您还可以执行以下操作:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
回答by Haacked
You can also just return string if you know that's the only thing the method will ever return. For example:
如果您知道这是该方法将永远返回的唯一内容,您也可以只返回字符串。例如:
public string MyActionName() {
return "Hi there!";
}
回答by Madhav Singh Raghav
public ActionResult GetAjaxValue()
{
return Content("string value");
}
回答by Kekule
public JsonResult GetAjaxValue()
{
return Json("string value", JsonRequetBehaviour.Allowget);
}
回答by Hyman Miller
As of 2020, using ContentResultis still the right approach as proposed above, but the usage is as follows:
到2020年,使用ContentResult仍然是上面提出的正确方法,但用法如下:
return new System.Web.Mvc.ContentResult
{
Content = "Hi there! ?",
ContentType = "text/plain; charset=utf-8"
}
回答by ahmed khattab
there is 2 way to return a string from controller to the view
有两种方法可以将字符串从控制器返回到视图
first
第一的
you could return only string but will not be included in html file it will be jus string appear in browser
您可以只返回字符串,但不会包含在 html 文件中,它将是 jus 字符串出现在浏览器中
second
第二
could return a string as object of View Result
可以返回一个字符串作为查看结果的对象
here is the code samples to do this
这是执行此操作的代码示例
public class HomeController : Controller
{
// GET: Home
// this will mreturn just 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", (object)s);
}
}
in view file to run AutoPropertyit will redirect you to Resultview and will send s
code to view
鉴于文件运行AutoProperty将您重定向到结果视图,并将派小号
代码视图
<!--this to make this file accept string as model-->
@model string
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Result</title>
</head>
<body>
<!--this is for represent the string -->
@Model
</body>
</html>
i run it at http://localhost:60227/Home/AutoProperty

