ASP.NET Acciones del controlador MVC que devuelven JSON o html parcial


Estoy tratando de crear acciones de controlador que devolverán JSON o html parcial dependiendo de un parámetro. ¿Cuál es la mejor manera de obtener el resultado devuelto a una página MVC de forma asíncrona?

Author: tereško, 2008-10-23

11 answers

En tu método de acción, devuelve Json(object) para devolver JSON a tu página.

public ActionResult SomeActionMethod() {
  return Json(new {foo="bar", baz="Blech"});
}

Luego simplemente llame al método action usando Ajax. Puede usar uno de los métodos auxiliares de la página de vista, como

<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>

SomeMethod sería un método javascript que luego evalúa el objeto Json devuelto.

Si desea devolver una cadena simple, puede usar el ContentResult:

public ActionResult SomeActionMethod() {
    return Content("hello world!");
}

ContentResult por defecto devuelve un text/plain como su ContentType.
Esto es se puede sobrecargar así que también puedes hacer:

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
 470
Author: Haacked,
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-08-07 19:25:30

Creo que debería considerar los tipos de aceptación de la solicitud. Lo estoy usando en mi proyecto actual para devolver el tipo de contenido correcto de la siguiente manera.

Su acción en el controlador puede probarlo como en el objeto de solicitud

if (Request.AcceptTypes.Contains("text/html")) {
   return View();
}
else if (Request.AcceptTypes.Contains("application/json"))
{
   return Json( new { id=1, value="new" } );
}
else if (Request.AcceptTypes.Contains("application/xml") || 
         Request.AcceptTypes.Contains("text/xml"))
{
   //
}

Luego puede implementar el aspx de la vista para atender el caso de respuesta xhtml parcial.

Luego, en jQuery puede obtenerlo pasando el parámetro type como json:

$.get(url, null, function(data, textStatus) {
        console.log('got %o with status %s', data, textStatus);
        }, "json"); // or xml, html, script, json, jsonp or text

Espero que esto ayude James

 106
Author: James Green,
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
2012-08-08 13:33:28

Otra buena forma de tratar los datos JSON es usando la función getJSON de jQuery. Puede llamar a la

public ActionResult SomeActionMethod(int id) 
{ 
    return Json(new {foo="bar", baz="Blech"});
}

Método del método getJSON de jquery simplemente...

$.getJSON("../SomeActionMethod", { id: someId },
    function(data) {
        alert(data.foo);
        alert(data.baz);
    }
);
 74
Author: SaaS Developer,
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
2014-05-12 06:32:16

Encontré un par de problemas al implementar MVC ajax GET calls con jQuery que me causaron dolores de cabeza para compartir soluciones aquí.

  1. Asegúrese de incluir el tipo de datos "json" en la llamada ajax. Esto analizará automáticamente el objeto JSON devuelto (dado que el servidor devuelve json válido).
  2. Incluir el JsonRequestBehavior.AllowGet; sin este MVC estaba devolviendo un error HTTP 500 (con dataType: json especificado en el cliente).
  3. Añadir cache: false al $.llamada ajax, de lo contrario será finalmente Respuestas HTTP 304 (en lugar de respuestas HTTP 200) y el servidor no procesará su solicitud.
  4. Finalmente, el json distingue entre mayúsculas y minúsculas, por lo que la carcasa de los elementos debe coincidir en el lado del servidor y el lado del cliente.

Ejemplo de jQuery:

$.ajax({
  type: 'get',
  dataType: 'json',
  cache: false,
  url: '/MyController/MyMethod',
  data: { keyid: 1, newval: 10 },
  success: function (response, textStatus, jqXHR) {
    alert(parseInt(response.oldval) + ' changed to ' + newval);                                    
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert('Error - ' + errorThrown);
  }
});

Código MVC de muestra:

[HttpGet]
public ActionResult MyMethod(int keyid, int newval)
{
  var oldval = 0;

  using (var db = new MyContext())
  {
    var dbRecord = db.MyTable.Where(t => t.keyid == keyid).FirstOrDefault();

    if (dbRecord != null)
    {
      oldval = dbRecord.TheValue;
      dbRecord.TheValue = newval;
      db.SaveChanges();
    }
  }

    return Json(new { success = true, oldval = oldval},
                JsonRequestBehavior.AllowGet);
}
 42
Author: Shane,
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
2018-01-23 12:05:40

Para responder la otra mitad de la pregunta, puedes llamar:

return PartialView("viewname");

Cuando desea devolver HTML parcial. Solo tendrá que encontrar alguna manera de decidir si la solicitud quiere JSON o HTML, tal vez basado en una parte/parámetro de URL.

 13
Author: Brad Wilson,
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
2008-10-23 01:25:39

Solución alternativa con marco de incodificación

Action return json

Controlador

    [HttpGet]
    public ActionResult SomeActionMethod()
    {
        return IncJson(new SomeVm(){Id = 1,Name ="Inc"});
    }

Razor page

@using (var template = Html.Incoding().ScriptTemplate<SomeVm>("tmplId"))
{
    using (var each = template.ForEach())
    {
        <span> Id: @each.For(r=>r.Id) Name: @each.For(r=>r.Name)</span>
    }
}

@(Html.When(JqueryBind.InitIncoding)
  .Do()
  .AjaxGet(Url.Action("SomeActionMethod","SomeContoller"))
  .OnSuccess(dsl => dsl.Self().Core()
                              .Insert
                              .WithTemplate(Selector.Jquery.Id("tmplId"))
                              .Html())
  .AsHtmlAttributes()
  .ToDiv())

Action return html

Controlador

    [HttpGet]
    public ActionResult SomeActionMethod()
    {
        return IncView();
    }

Razor page

@(Html.When(JqueryBind.InitIncoding)
  .Do()
  .AjaxGet(Url.Action("SomeActionMethod","SomeContoller"))
  .OnSuccess(dsl => dsl.Self().Core().Insert.Html())
  .AsHtmlAttributes()
  .ToDiv())
 7
Author: Vlad,
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
2013-05-06 06:39:03

Es posible que desee echar un vistazo a este artículo muy útil que cubre esto muy bien!

Solo pensé que podría ayudar a las personas que buscan una buena solución a este problema.

Http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx

 6
Author: Paul Hinett,
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
2012-08-08 13:33:51

Para las personas que han actualizado a MVC 3 aquí es una manera ordenada Usando MVC3 y Json

 4
Author: Sarath,
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
2011-03-17 10:19:30

PartialViewResult y JSONReuslt heredan de la clase base ActionResult. así que si el tipo de retorno se decide dinámicamente declarar salida método como ActionResult.

public ActionResult DynamicReturnType(string parameter)
        {
            if (parameter == "JSON")
                return Json("<JSON>", JsonRequestBehavior.AllowGet);
            else if (parameter == "PartialView")
                return PartialView("<ViewName>");
            else
                return null;


        }
 3
Author: Anil Vaddepally,
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-08-08 05:35:38
    public ActionResult GetExcelColumn()
    {            
            List<string> lstAppendColumn = new List<string>();
            lstAppendColumn.Add("First");
            lstAppendColumn.Add("Second");
            lstAppendColumn.Add("Third");
  return Json(new { lstAppendColumn = lstAppendColumn,  Status = "Success" }, JsonRequestBehavior.AllowGet);
            }
        }
 2
Author: sakthi,
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-09-07 11:13:25

Flexible approach to produce different outputs based on the request

public class AuctionsController : Controller
{
  public ActionResult Auction(long id)
  {
    var db = new DataContext();
    var auction = db.Auctions.Find(id);

    // Respond to AJAX requests
    if (Request.IsAjaxRequest())
      return PartialView("Auction", auction);

    // Respond to JSON requests
    if (Request.IsJsonRequest())
      return Json(auction);

    // Default to a "normal" view with layout
    return View("Auction", auction);
  }
}

El método Request.IsAjaxRequest() es bastante simple: simplemente comprueba los encabezados HTTP para la solicitud entrante para ver si el valor del encabezado X-Requested-With es XMLHttpRequest, que es agregado automáticamente por la mayoría de los navegadores y marcos AJAX.

Método de extensión personalizada para comprobar si la solicitud es para json o no para que podamos llamarla desde cualquier lugar, al igual que la Solicitud.Extensión IsAjaxRequest() método:

using System;
using System.Web;

public static class JsonRequestExtensions
{
  public static bool IsJsonRequest(this HttpRequestBase request)
  {
    return string.Equals(request["format"], "json");
  }
}

Fuente: https://www.safaribooksonline.com/library/view/programming-aspnet-mvc/9781449321932/ch06.html#_javascript_rendering

 0
Author: Mannan Bahelim,
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
2018-03-28 09:35:43