问题
In my AJAX call, I want to return a string value back to the calling page.
Should I use ActionResult
or just return a string?
回答1:
You can just use the ContentResult to return a plain string:
public ActionResult Temp() {
return Content("Hi there!");
}
ContentResult by default returns a text/plain
as its contentType. This is overloadable so you can also do:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
回答2:
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!";
}
回答3:
public ActionResult GetAjaxValue()
{
return Content("string value");
}
回答4:
public JsonResult GetAjaxValue()
{
return Json("string value", JsonRequetBehaviour.Allowget);
}
回答5:
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
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 AutoProperty it will redirect you to Result view and will send s
code to view
<!--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
来源:https://stackoverflow.com/questions/553936/in-mvc-how-do-i-return-a-string-result