In MVC, how do I return a string result?

做~自己de王妃 提交于 2019-11-26 14:53:52
swilliams

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 ActionResult GetAjaxValue()
{
   return Content("string value");
}
Kekule
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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!