我试图创建控制器动作,根据参数返回JSON或部分html。异步将结果返回到MVC页面的最佳方法是什么?
当前回答
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);
}
}
其他回答
我认为您应该考虑请求的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
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);
}
}
与编码框架的替代解决方案
操作返回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())
在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");
我发现用JQuery实现MVC ajax GET调用的几个问题,这让我头疼,所以在这里分享解决方案。
Make sure to include the data type "json" in the ajax call. This will automatically parse the returned JSON object for you (given the server returns valid json). Include the JsonRequestBehavior.AllowGet; without this MVC was returning a HTTP 500 error (with dataType: json specified on the client). Add cache: false to the $.ajax call, otherwise you will ultimately get HTTP 304 responses (instead of HTTP 200 responses) and the server will not process your request. Finally, the json is case sensitive, so the casing of the elements needs to match on the server side and client side.
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);
}
推荐文章
- asp.net MVC中的@RenderSection是什么
- 在哪里放置AutoMapper.CreateMaps?
- 我如何提高ASP。NET MVC应用程序性能?
- 在ASP中设置Access-Control-Allow-OriginNet MVC -最简单的方法
- 如何在剃刀视图上引用.css文件?
- Ajax成功事件不工作
- JWT vs cookie用于基于令牌的身份验证
- JQ:选择多个条件
- 什么是HTTP中的“406-不可接受的响应”?
- ASP。NET Core返回带有状态码的JSON
- 我如何添加环境变量启动。VSCode中的json
- PostgreSQL返回JSON数组的结果集?
- 事件。returnValue已弃用。请使用标准的event.preventDefault()
- HTTP POST在Java中使用JSON
- 如何指定杰克逊只使用字段-最好是全局