在我的AJAX调用中,我想将一个字符串值返回到调用页面。
我应该使用ActionResult还是只返回一个字符串?
在我的AJAX调用中,我想将一个字符串值返回到调用页面。
我应该使用ActionResult还是只返回一个字符串?
当前回答
你也可以只返回string如果你知道这是方法唯一返回的东西。例如:
public string MyActionName() {
return "Hi there!";
}
其他回答
截至2020年,使用ContentResult仍然是上面提出的正确方法,但用法如下:
return new System.Web.Mvc.ContentResult
{
Content = "Hi there! ☺",
ContentType = "text/plain; charset=utf-8"
}
public JsonResult GetAjaxValue()
{
return Json("string value", JsonRequetBehaviour.Allowget);
}
public ActionResult GetAjaxValue()
{
return Content("string value");
}
你也可以只返回string如果你知道这是方法唯一返回的东西。例如:
public string MyActionName() {
return "Hi there!";
}
你可以使用ContentResult返回一个普通字符串:
public ActionResult Temp() {
return Content("Hi there!");
}
ContentResult默认返回一个文本/纯文本作为它的contentType。这是可重载的,所以你还可以做:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");