Nat*_*anD 393 ajax asp.net-mvc json asp.net-ajax
我正在尝试创建控制器操作,它将返回JSON或部分html,具体取决于参数.将结果异步返回到MVC页面的最佳方法是什么?
Haa*_*ked 502
在您的action方法中,返回Json(object)以将JSON返回到您的页面.
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
Run Code Online (Sandbox Code Playgroud)
然后使用Ajax调用action方法.您可以使用ViewPage中的一个辅助方法,例如
<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
Run Code Online (Sandbox Code Playgroud)
SomeMethod将是一个javascript方法,然后评估返回的Json对象.
如果要返回纯字符串,可以使用ContentResult:
public ActionResult SomeActionMethod() {
return Content("hello world!");
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,ContentResult返回text/plain作为其contentType.
这是多重的,所以你也可以这样做:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
Run Code Online (Sandbox Code Playgroud)
小智 111
我认为你应该考虑请求的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"))
{
//
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以实现视图的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
Run Code Online (Sandbox Code Playgroud)
希望这有助于詹姆斯
Saa*_*per 76
处理JSON数据的另一个好方法是使用JQuery getJSON函数.你可以打电话给
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
Run Code Online (Sandbox Code Playgroud)
来自jquery getJSON方法的方法只需...
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
Run Code Online (Sandbox Code Playgroud)
Sha*_*ane 49
我发现使用JQuery实现MVC ajax GET调用的几个问题导致我头疼,所以在这里共享解决方案.
JsonRequestBehavior.AllowGet; 没有这个MVC返回HTTP 500错误(dataType: json在客户端上指定).cache: false到$ .ajax调用,否则您最终将获得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);
}
});
Run Code Online (Sandbox Code Playgroud)
示例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);
}
Run Code Online (Sandbox Code Playgroud)
Bra*_*son 13
要回答问题的另一半,您可以致电:
return PartialView("viewname");
Run Code Online (Sandbox Code Playgroud)
当你想要返回部分HTML时.您只需找到一些方法来确定请求是否需要JSON或HTML,可能基于URL部分/参数.
小智 7
带有编码框架的替代解决方案
行动返回json
调节器
[HttpGet]
public ActionResult SomeActionMethod()
{
return IncJson(new SomeVm(){Id = 1,Name ="Inc"});
}
Run Code Online (Sandbox Code Playgroud)
剃刀页面
@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())
Run Code Online (Sandbox Code Playgroud)
动作返回html
调节器
[HttpGet]
public ActionResult SomeActionMethod()
{
return IncView();
}
Run Code Online (Sandbox Code Playgroud)
剃刀页面
@(Html.When(JqueryBind.InitIncoding)
.Do()
.AjaxGet(Url.Action("SomeActionMethod","SomeContoller"))
.OnSuccess(dsl => dsl.Self().Core().Insert.Html())
.AsHtmlAttributes()
.ToDiv())
Run Code Online (Sandbox Code Playgroud)
你可能想看看这篇非常有用的文章,它很好地涵盖了这一点!
只是认为它可以帮助人们寻找这个问题的一个很好的解决方案.
http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx
小智 5
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
548505 次 |
| 最近记录: |