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

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?

转载于:https://stackoverflow.com/questions/553936/in-mvc-how-do-i-return-a-string-result

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

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!";
}
public JsonResult GetAjaxValue() 
{
  return Json("string value", JsonRequetBehaviour.Allowget); 
}

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