代码之家  ›  专栏  ›  技术社区  ›  NathanD

返回JSON或部分html的ASP.NET MVC控制器操作

  •  376
  • NathanD  · 技术社区  · 17 年前

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

    11 回复  |  直到 14 年前
        1
  •  544
  •   Eduardo Molteni    17 年前

    在您的操作方法中,返回Json(对象)以将Json返回到页面。

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

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

    如果要返回普通字符串,可以使用ContentResult:

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


    这是可重载的,因此您还可以执行以下操作:

    return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
    
        2
  •  113
  •   yoozer8    14 年前

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

    您在控制器上的操作可以像在请求对象上一样对其进行测试

    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
    

    希望这有帮助

        3
  •  82
  •   radbyx Matt    12 年前

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

    通过简单地。。。

    $.getJSON("../SomeActionMethod", { id: someId },
        function(data) {
            alert(data.foo);
            alert(data.baz);
        }
    );
    
        4
  •  53
  •   Shanerk    8 年前

    我发现使用JQuery实现MVC ajax GET调用时出现了一些问题,这让我很头疼,所以在这里分享解决方案。

    1. 确保在ajax调用中包含数据类型“json”。这将自动为您解析返回的JSON对象(假定服务器返回有效的JSON)。
    2. 包括 JsonRequestBehavior.AllowGet ; 如果没有此MVC,则返回HTTP 500错误(带有 dataType: json 在客户端上指定)。
    3. 添加 cache: false 对于$.ajax调用,否则最终将得到HTTP 304响应(而不是HTTP 200响应),服务器将不会处理您的请求。
    4. 最后,json是区分大小写的,因此元素的大小写需要在服务器端和客户端匹配。

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

    MVC代码示例:

    [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);
    }
    
        5
  •  12
  •   Brad Wilson    17 年前

    要回答问题的另一半,您可以致电:

    return PartialView("viewname");
    

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

        6
  •  7
  •   Vlad    13 年前

    incoding framework

    操作返回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())
    
        7
  •  6
  •   yoozer8    14 年前

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

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

        8
  •  5
  •   Anil Vaddepally    9 年前

    PartialViewResult和JSONReuslt继承自基类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;
    
    
            }
    
        9
  •  3
  •   Sarath    15 年前
        10
  •  2
  •   sakthi    9 年前
        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);
                }
            }
    
        11
  •  1
  •   Mannan Bahelim    8 年前

    灵活的方法,根据请求生成不同的输出

    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,以便我们可以从任何位置调用它,就像请求一样。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