首页 文章

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

提问于
浏览
570

在我的AJAX调用中,我想将一个字符串值返回给调用页面 .

我应该使用 ActionResult 还是只返回一个字符串?

5 回答

  • 106
    public JsonResult GetAjaxValue() 
    {
      return Json("string value", JsonRequetBehaviour.Allowget); 
    }
    
  • 973

    您可以使用ContentResult返回纯字符串:

    public ActionResult Temp() {
        return Content("Hi there!");
    }
    

    ContentResult默认返回 text/plain 作为contentType . 这是超载的,所以你也可以这样做:

    return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
    
  • 0

    如果您知道方法将返回的唯一内容,您也可以返回字符串 . 例如:

    public string MyActionName() {
      return "Hi there!";
    }
    
  • 6
    public ActionResult GetAjaxValue()
    {
       return Content("string value");
    }
    
  • -1

    有两种方法可以将一个字符串从控制器返回到视图

    第一

    你只能返回字符串,但不会包含在html文件中,它将是jus字符串出现在浏览器中

    第二

    可以返回一个字符串作为View Result的对象

    这是执行此操作的代码示例

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

    在视图文件中运行 AutoProperty 它会将您重定向到 Result 视图并将发送 s
    要查看的代码

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

    我在http:// localhost:60227 / Home / AutoProperty上运行它

相关问题