Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ajax 返回JSON或部分html的ASP.NET MVC控制器操作_Ajax_Asp.net Mvc_Json_Asp.net Ajax - Fatal编程技术网

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

Ajax 返回JSON或部分html的ASP.NET MVC控制器操作,ajax,asp.net-mvc,json,asp.net-ajax,Ajax,Asp.net Mvc,Json,Asp.net Ajax,我试图创建控制器操作,根据参数返回JSON或部分html。将结果异步返回到MVC页面的最佳方式是什么?在操作方法中,返回Json(对象)以将Json返回到页面 public ActionResult SomeActionMethod() { return Json(new {foo="bar", baz="Blech"}); } 然后使用Ajax调用action方法。您可以使用ViewPage中的一个帮助器方法,例如 <%= Ajax.ActionLink("SomeActionMe

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

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

public ActionResult SomeActionMethod() {
  return Json(new {foo="bar", baz="Blech"});
}
然后使用Ajax调用action方法。您可以使用ViewPage中的一个帮助器方法,例如

<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
默认情况下,ContentResult返回文本/纯文本作为其contentType。
这是可重载的,因此您还可以执行以下操作:

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
返回内容(“这是格式不好的xml。”,“text/xml”);

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

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

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

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

return PartialView("viewname");

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

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

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

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
希望这有帮助
James

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

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


对于升级到MVC 3的用户,这里有一个简单的方法

使用

操作返回json

控制器

    [HttpGet]
    public ActionResult SomeActionMethod()
    {
        return IncJson(new SomeVm(){Id = 1,Name ="Inc"});
    }
    [HttpGet]
    public ActionResult SomeActionMethod()
    {
        return IncView();
    }
剃须刀页面

@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.When(JqueryBind.InitIncoding)
  .Do()
  .AjaxGet(Url.Action("SomeActionMethod","SomeContoller"))
  .OnSuccess(dsl => dsl.Self().Core().Insert.Html())
  .AsHtmlAttributes()
  .ToDiv())
剃须刀页面

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

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

  • 确保在ajax调用中包含数据类型“json”。这将自动为您解析返回的JSON对象(假定服务器返回有效的JSON)
  • 包括
    JsonRequestBehavior.AllowGet
    ;如果没有此MVC,则返回HTTP 500错误(在客户端上指定了
    dataType:json
  • 在$.ajax调用中添加
    cache:false
    ,否则最终将得到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);
    }
    

    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;
    
    
            }
    
    public ActionResult DynamicReturnType(字符串参数)
    {
    如果(参数==“JSON”)
    返回Json(“,JsonRequestBehavior.AllowGet);
    else if(参数==“PartialView”)
    返回部分视图(“”);
    其他的
    返回null;
    }
    
    公共操作结果GetExcelColumn()
    {            
    List lstAppendColumn=新列表();
    第1列。添加(“第一列”);
    添加第二列(“第二列”);
    第1列。添加(“第三列”);
    返回Json(新的{lstAppendColumn=lstAppendColumn,Status=“Success”},JsonRequestBehavior.AllowGet);
    }
    }
    
    根据请求生成不同输出的灵活方法

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

    来源:

    那么这个问题还没有答案吗?这并没有回答问题。他正在寻找一个ajax请求,以使用PartialView获取html。除非您使用ajax调用从操作方法返回视图,否则view需要页面刷新!这实际上并没有回答问题,是吗?这肯定很有用,但正如brad所说,你需要找出他们的要求,并相应地返回结果。请参阅我的有点相关的(也就是让我来到这里的那个)问题。如果你找到答案,请将其链接到问题本身。我也不认为检查这个答案是正确的。Json类的完全限定名是什么?感谢James,这对于使用相同的控制器操作创建某种网站和REST API可能非常有用。如果我的控制器中有许多类似的方法,有没有更通用的方法?Json类在哪个命名空间中?project.json的依赖关系是什么?提前感谢(在System.Web.Mvc.dll中)@andriethank你,找到了。可能会更新答案以反映新的API?顺便说一句,我使用的是dotnet core,它是Microsoft.AspNetCore.Mvc.JsonResult。你也可以使用与本文在Mvc 2中相同的技术。这根本不能回答问题。@aaronauth实际上是第一部分
    返回Json(new{foo=“bar”,baz=“Blech”})可以!还考虑$POST(ASP.NET MVC默认值以禁用JSON-GET请求以保证安全)。您可以添加一些关于此操作的信息吗?由于代码显示返回JSON,返回类型应该是JSONREST,而不是AccRebug结果。