我试图创建控制器动作,根据参数返回JSON或部分html。异步将结果返回到MVC页面的最佳方法是什么?


当前回答

PartialViewResult和jsonresult继承自基类ActionResult。因此,如果返回类型是动态决定的,则将方法输出声明为ActionResult。

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


        }

其他回答

与编码框架的替代解决方案

操作返回json

控制器

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

剃须刀页面

@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())

操作返回html

控制器

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

剃须刀页面

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

我认为您应该考虑请求的AcceptTypes。我在我当前的项目中使用它来返回正确的内容类型,如下所示。

你在控制器上的动作可以像在请求对象上一样测试它

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"))
{
   //
}

然后,您可以实现视图的aspx来满足部分xhtml响应的情况。

然后在jQuery中,你可以将类型参数作为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

灵活的方法,产生不同的输出根据要求

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

request . isajaxrequest()方法非常简单:它只是检查传入请求的HTTP报头,以查看X-Requested-With报头的值是否为XMLHttpRequest,大多数浏览器和AJAX框架都会自动添加该报头。

自定义扩展方法来检查请求是否为json,以便我们可以从任何地方调用它,就像request . isajaxrequest()扩展方法一样:

using System;
using System.Web;

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

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

要回答问题的另一半,你可以拨打:

return PartialView("viewname");

当你想返回部分HTML时。您只需要找到某种方法来决定请求是想要JSON还是HTML,可能是基于URL部分/参数。

你可能想看看这篇非常有用的文章,它很好地介绍了这一点!

只是觉得它可能会帮助人们找到解决这个问题的好办法。

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