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?
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?
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!";
}
As of 2020, using ContentResult is still the right approach as proposed above, but the usage is as follows:
return new System.Web.Mvc.ContentResult
{
Content = "Hi there! ☺",
ContentType = "text/plain; charset=utf-8"
}
you can just return a string but some API's do not like it as the response type is not fitting the response,
[Produces("text/plain")]
public string Temp() {
return Content("Hi there!");
}
this usually does the trick