首页 文章

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

提问于
浏览
374

我正在尝试创建控制器操作,它将返回JSON或部分html,具体取决于参数 . 将结果异步返回到MVC页面的最佳方法是什么?

11 回答

  • 106
    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);
                }
            }
    
  • 44

    在您的action方法中,返回Json(object)以将JSON返回到您的页面 .

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

    然后使用Ajax调用action方法 . 您可以使用ViewPage中的一个辅助方法,例如

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

    SomeMethod将是一个javascript方法,然后评估返回的Json对象 .

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

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

    默认情况下,ContentResult返回text / plain作为其contentType .
    这是超载的,所以你也可以这样做:

    return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
    
  • 13

    我认为你应该考虑请求的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
    

    希望这有助于詹姆斯

  • 7

    处理JSON数据的另一个好方法是使用JQuery getJSON函数 . 你可以打电话给

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

    来自jquery getJSON方法的方法只需...

    $.getJSON("../SomeActionMethod", { id: someId },
        function(data) {
            alert(data.foo);
            alert(data.baz);
        }
    );
    
  • 474

    我发现使用JQuery实现MVC ajax GET调用的几个问题导致我头疼,所以在这里共享解决方案 .

    • 确保在ajax调用中包含数据类型"json" . 这将自动为您解析返回的JSON对象(假设服务器返回有效的json) .

    • 包括 JsonRequestBehavior.AllowGet ;没有这个MVC返回HTTP 500错误(在客户端指定 dataType: json ) .

    • cache: false 添加到$ .ajax调用,否则最终将获得HTTP 304响应(而不是HTTP 200响应),服务器将不会处理您的请求 .

    • 最后,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);
    }
    
  • 74

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

    return PartialView("viewname");
    

    当你想要返回部分HTML时 . 您只需要找到一些方法来决定请求是否需要JSON或HTML,可能是基于URL部分/参数 .

  • 4

    incoding framework的替代解决方案

    动作返回json

    Controller

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

    动作返回html

    Controller

    [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())
    
  • 2

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

    只是认为它可以帮助人们寻找这个问题的一个很好的解决方案 .

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

  • 0

    对于那些升级到MVC 3的人来说这是一个很好的方式Using MVC3 and Json

  • 3

    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;
    
    
            }
    
  • 6

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

    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

相关问题