我试图创建控制器动作,根据参数返回JSON或部分html。异步将结果返回到MVC页面的最佳方法是什么?
当前回答
在action方法中,返回Json(object)将Json返回到页面。
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
然后使用Ajax调用action方法。您可以使用ViewPage中的一个辅助方法,例如
<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
SomeMethod将是一个javascript方法,然后计算返回的Json对象。
如果你想返回一个普通的字符串,你可以使用ContentResult:
public ActionResult SomeActionMethod() {
return Content("hello world!");
}
ContentResult默认返回一个文本/纯文本作为它的contentType。 这是可重载的,所以你还可以做:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
其他回答
另一种处理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);
}
);
灵活的方法,产生不同的输出根据要求
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
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);
}
}
在action方法中,返回Json(object)将Json返回到页面。
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
然后使用Ajax调用action方法。您可以使用ViewPage中的一个辅助方法,例如
<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
SomeMethod将是一个javascript方法,然后计算返回的Json对象。
如果你想返回一个普通的字符串,你可以使用ContentResult:
public ActionResult SomeActionMethod() {
return Content("hello world!");
}
ContentResult默认返回一个文本/纯文本作为它的contentType。 这是可重载的,所以你还可以做:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
PartialViewResult和jsonresult继承自基类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;
}
推荐文章
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- ASP。NET Identity DbContext混淆
- Django CSRF检查Ajax POST请求失败
- jQuery Ajax调用和Html.AntiForgeryToken()
- 将对象序列化为JSON
- Gzip的JavaScript实现
- node.js TypeError:路径必须是绝对路径或指定根路径到res.sendFile[解析JSON失败]
- Python json。loads显示ValueError:额外数据
- JSON省略了Infinity和NaN;JSON在ECMAScript中的状态?
- 获取API请求超时?
- console.log(result)输出[object对象]。我如何得到result。name?
- 确定$。Ajax错误是一个超时
- java8 LocalDate Jackson格式
- 在Go中使用JSON Marshal的小写JSON键名
- jQuery发布JSON