我试图创建控制器动作,根据参数返回JSON或部分html。异步将结果返回到MVC页面的最佳方法是什么?
当前回答
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;
}
其他回答
要回答问题的另一半,你可以拨打:
return PartialView("viewname");
当你想返回部分HTML时。您只需要找到某种方法来决定请求是想要JSON还是HTML,可能是基于URL部分/参数。
我发现用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);
}
我认为您应该考虑请求的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);
}
);
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);
}
}
推荐文章
- 如果我使用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