En MVC, ¿cómo devuelvo un resultado de cadena?
En mi llamada AJAX, quiero devolver un valor de cadena a la página de llamada.
¿Debo usar ActionResult
o simplemente devolver una cadena?
5 answers
Solo puede usar el ContentResult
para devolver una cadena simple:
public ActionResult Temp() {
return Content("Hi there!");
}
ContentResult
por defecto devuelve un text/plain
como contentType. Esto es sobrecargable, así que también puedes hacer:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-29 11:27:08
También puede devolver string si sabe que es lo único que el método devolverá. Por ejemplo:
public string MyActionName() {
return "Hi there!";
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-16 23:29:58
public ActionResult GetAjaxValue()
{
return Content("string value");
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-11 03:16:36
public JsonResult GetAjaxValue()
{
return Json("string value", JsonRequetBehaviour.Allowget);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-16 13:20:28
Hay 2 maneras de devolver una cadena desde el controlador a la vista
Primero
Puede devolver solo una cadena, pero no se incluirá en html archivo será jus cadena aparecerá en el navegador
segundo
Podría devolver una cadena como objeto de Vista Resultado
Aquí están las muestras de código para hacer esto
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);
}
}
En el archivo de vista para ejecutar AutoProperty le redirigirá a Result view y enviar s
código a ver
<!--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>
Lo corro en http://localhost:60227/Home/AutoProperty
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-10 16:58:12