我正在尝试创建控制器操作,根据参数返回JSON或部分HTML。什么是将结果异步返回到MVC页面的最佳方法?
我应该如何将结果异步返回至MVC页面?我正在尝试创建控制器操作,根据参数返回JSON或部分HTML。什么是将结果异步返回到MVC页面的最佳方法?
我应该如何将结果异步返回至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中,您可以传递type参数作为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);
}
);
return Json(new {foo="bar", baz="Blech"});
就是! - SparKJsonRequestBehavior.AllowGet
;没有这个,MVC会返回HTTP 500错误(在客户端指定dataType:json
)。cache:false
,否则您最终会收到HTTP 304响应(而不是HTTP 200响应),服务器将无法处理您的请求。示例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);
}
回答问题的另一半,您可以拨打以下电话:
return PartialView("viewname");
当你想返回部分HTML时,你只需要找到某种方法来决定请求是想要JSON还是HTML,也许可以根据URL的一部分或参数来确定。
使用incoding framework进行替代的解决方案
Action返回json格式数据
控制器(Controller)
[HttpGet]
public ActionResult SomeActionMethod()
{
return IncJson(new SomeVm(){Id = 1,Name ="Inc"});
}
Razor页面
@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();
}
Razor页面
@(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 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框架都会自动添加该标头。Request.IsAjaxRequest()
扩展方法一样。using System;
using System.Web;
public static class JsonRequestExtensions
{
public static bool IsJsonRequest(this HttpRequestBase request)
{
return string.Equals(request["format"], "json");
}
}
该页面讲解了在 ASP.NET MVC 中如何使用 JavaScript 渲染视图。你可以使用 jQuery 或纯 JavaScript 来完成这个过程。其中,使用 jQuery 会更加简单易用。