In MVC, how do I return a string result?

2020-01-24 01:38发布

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?

5条回答
Explosion°爆炸
2楼-- · 2020-01-24 02:20

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!";
}
查看更多
Rolldiameter
3楼-- · 2020-01-24 02:21
public JsonResult GetAjaxValue() 
{
  return Json("string value", JsonRequetBehaviour.Allowget); 
}
查看更多
男人必须洒脱
4楼-- · 2020-01-24 02:22

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

查看更多
Juvenile、少年°
5楼-- · 2020-01-24 02:30
public ActionResult GetAjaxValue()
{
   return Content("string value");
}
查看更多
迷人小祖宗
6楼-- · 2020-01-24 02:35

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");
查看更多
登录 后发表回答