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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/227624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:08:29  来源:igfitidea点击:

ASP.NET MVC controller actions that return JSON or partial html

ajaxasp.net-mvcjsonasp.net-ajax

提问by NathanD

I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?

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

回答by Haacked

In your action method, return Json(object) to return JSON to your page.

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

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

Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as

然后只需使用 Ajax 调用 action 方法。您可以使用 ViewPage 中的一种辅助方法,例如

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

SomeMethod would be a javascript method that then evaluates the Json object returned.

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

If you want to return a plain string, you can just use the ContentResult:

如果你想返回一个普通的字符串,你可以只使用 ContentResult:

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

ContentResult by default returns a text/plain as its contentType.
This is overloadable so you can also do:

ContentResult 默认返回一个 text/plain 作为它的 contentType。
这是可重载的,因此您还可以执行以下操作:

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

回答by James Green

I think you should consider the AcceptTypes of the request. I am using it in my current project to return the correct content type as follows.

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

Your action on the controller can test it as on the request object

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

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

You can then implement the aspx of the view to cater for the partial xhtml response case.

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

Then in jQuery you can fetch it passing the type parameter as json:

然后在 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

Hope this helps James

希望这能帮助詹姆斯

回答by SaaS Developer

Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the

另一个处理 JSON 数据的好方法是使用 JQuery getJSON 函数。您可以拨打

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

Method from the jquery getJSON method by simply...

来自 jquery getJSON 方法的方法简单地...

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

回答by Shane

I found a couple of issues implementing MVC ajax GET calls with JQuery that caused me headaches so sharing solutions here.

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

  1. Make sure to include the data type "json" in the ajax call. This will automatically parse the returned JSON object for you (given the server returns valid json).
  2. Include the JsonRequestBehavior.AllowGet; without this MVC was returning a HTTP 500 error (with dataType: jsonspecified on the client).
  3. Add cache: falseto the $.ajax call, otherwise you will ultimately get HTTP 304 responses (instead of HTTP 200 responses) and the server will not process your request.
  4. Finally, the json is case sensitive, so the casing of the elements needs to match on the server side and client side.
  1. 确保在 ajax 调用中包含数据类型“json”。这将自动为您解析返回的 JSON 对象(假设服务器返回有效的 json)。
  2. 包括JsonRequestBehavior.AllowGet; 没有这个 MVC 会返回 HTTP 500 错误(dataType: json在客户端指定)。
  3. 添加cache: false到 $.ajax 调用中,否则您最终将获得 HTTP 304 响应(而不是 HTTP 200 响应)并且服务器将不会处理您的请求。
  4. 最后,json 区分大小写,因此元素的大小写需要在服务器端和客户端匹配。

Sample JQuery:

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

Sample MVC code:

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

回答by Brad Wilson

To answer the other half of the question, you can call:

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

return PartialView("viewname");

when you want to return partial HTML. You'll just have to find some way to decide whether the request wants JSON or HTML, perhaps based on a URL part/parameter.

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

回答by Vlad

Alternative solution with incoding framework

带有编码框架的替代解决方案

Action return json

动作返回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())

Action return html

动作返回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())

回答by Paul Hinett

You may want to take a look at this very helpful article which covers this very nicely!

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

Just thought it might help people searching for a good solution to this problem.

只是认为它可能会帮助人们寻找解决此问题的好方法。

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

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

回答by Anil Vaddepally

PartialViewResult and JSONReuslt inherit from the base class ActionResult. so if return type is decided dynamically declare method output as ActionResult.

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;


        }

回答by Sarath

For folks who have upgraded to MVC 3 here is a neat way Using MVC3 and Json

对于已经升级到 MVC 3 的人来说,这是一种使用 MVC3 和 Json的巧妙方法

回答by sakthi

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