677

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?

4

7 回答 7

1151

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");
于 2009-02-16T17:47:51.753 回答
114

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!";
}
于 2009-02-16T23:29:58.390 回答
15
public ActionResult GetAjaxValue()
{
   return Content("string value");
}
于 2016-04-27T14:18:44.853 回答
3

As of 2020, using ContentResult is still the right approach as proposed above, but the usage is as follows:

return new System.Web.Mvc.ContentResult
{
    Content = "Hi there! ☺",
    ContentType = "text/plain; charset=utf-8"
}
于 2020-05-04T08:20:09.967 回答
1

There Are 2 ways to return a string from the controller to the view:

First

You could return only the string, but it will not be included in your .cshtml file. it will be just a string appearing in your browser.


Second

You could return a string as the Model object of View Result.

Here is the code sample to do this:

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

    }
}

In the view file to run AutoProperty, It will redirect you to the Result view and will send s
code to the view

<!--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>

I run this at http://localhost:60227/Home/AutoProperty.

于 2017-06-10T16:58:12.647 回答
0
public JsonResult GetAjaxValue() 
{
  return Json("string value", JsonRequetBehaviour.Allowget); 
}
于 2017-05-16T12:45:51.257 回答
0

you can just return a string but some API's do not like it as the response type is not fitting the response,

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

this usually does the trick

于 2022-01-17T14:01:52.517 回答