我正试图创建控制器动作,根据参数返回JSON或部分HTML。什么是最好的方法来获得异步返回到MVC页面的结果?
在你的动作方法中,返回Json(object)以返回JSON到你的页面。
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
然后用Ajax调用该动作方法即可。你可以使用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");
我认为你应该考虑请求的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
希望能帮到你 詹姆斯
另一个处理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);
}
);
我发现了几个用JQuery实现MVC ajax GET调用的问题,让我很头疼,所以在这里分享解决方案。
包括JsonRequestBehavior.AllowGet
。
如果没有这个MVC就会返回HTTP 500错误(在客户端指定了dataType: 在客户端指定了
json`)。)
在$.ajs中添加cache: 在$.ajax调用中加入
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);
}
有[编码框架]的替代解决办法[1]
Action return 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())
你可能想看看这篇非常有用的文章,它很好地涵盖了这一点!只是觉得它可能会帮助人们寻找这个问题的良好解决方案。
只是觉得它可能会帮助人们寻找解决这个问题的好办法。
http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx
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 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);
}
}
灵活的方法,可根据要求产生不同的产出。
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");
}
}