asp.net ajax 返回html,ajax - 返回JSON或部分htm的ASP.NET MVC控制器操作

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

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

11个解决方案

472 votes

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

public ActionResult SomeActionMethod() {

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

}

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

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

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

public ActionResult SomeActionMethod() {

return Content("hello world!");

}

默认情况下,ContentResult返回text / plain作为其contentType。

这是多重的,所以你也可以这样做:

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

Haacked answered 2019-01-26T23:08:56Z

106 votes

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

希望这可以帮助詹姆士

James Green answered 2019-01-26T23:09:48Z

74 votes

处理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);

}

);

SaaS Developer answered 2019-01-26T23:10:19Z

43 votes

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

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

包括cache: false; 没有这个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);

}

Shane answered 2019-01-26T23:11:20Z

13 votes

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

return PartialView("viewname");

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

Brad Wilson answered 2019-01-26T23:11:48Z

7 votes

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

行动返回json

调节器

[HttpGet]

public ActionResult SomeActionMethod()

{

return IncJson(new SomeVm(){Id = 1,Name ="Inc"});

}

剃刀页面

@using (var template = Html.Incoding().ScriptTemplate("tmplId"))

{

using (var each = template.ForEach())

{

Id: @each.For(r=>r.Id) Name: @each.For(r=>r.Name)

}

}

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

Vlad answered 2019-01-26T23:12:36Z

6 votes

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

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

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

Paul Hinett answered 2019-01-26T23:13:11Z

4 votes

对于已升级到MVC 3的人来说,这是一个很好的方式使用MVC3和Json

Sarath answered 2019-01-26T23:13:36Z

3 votes

PartialViewResult和JSONReuslt继承自基类ActionResult。 所以如果返回类型被决定动态声明方法输出为ActionResult。

public ActionResult DynamicReturnType(string parameter)

{

if (parameter == "JSON")

return Json("", JsonRequestBehavior.AllowGet);

else if (parameter == "PartialView")

return PartialView("");

else

return null;

}

Anil Vaddepally answered 2019-01-26T23:13:59Z

2 votes

public ActionResult GetExcelColumn()

{

List lstAppendColumn = new List();

lstAppendColumn.Add("First");

lstAppendColumn.Add("Second");

lstAppendColumn.Add("Third");

return Json(new { lstAppendColumn = lstAppendColumn, Status = "Success" }, JsonRequestBehavior.AllowGet);

}

}

sakthi answered 2019-01-26T23:14:14Z

0 votes

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

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]

Mannan Bahelim answered 2019-01-26T23:14:56Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值