2023-02-17 384
我正在尝试创建控制器操作,这将根据参数返回JSON或部分HTML.将结果的最佳方式异步返回到MVC页面?
在操作方法中,返回JSON(对象)将JSON返回到您的页面.
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
然后使用ajax调用Action方法.您可以使用来自视图的辅助方法之一,例如
<%= 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");
我认为您应该考虑请求的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);
}
);
以上所述是小编给大家介绍的返回JSON或部分HTML的ASP.NET MVC控制器动作,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!
原文链接:https://77isp.com/post/34186.html
=========================================
https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。
数据库技术 2022-03-28
网站技术 2022-11-26
网站技术 2023-01-07
网站技术 2022-11-17
Windows相关 2022-02-23
网站技术 2023-01-14
Windows相关 2022-02-16
Windows相关 2022-02-16
Linux相关 2022-02-27
数据库技术 2022-02-20
抠敌 2023年10月23日
嚼餐 2023年10月23日
男忌 2023年10月22日
瓮仆 2023年10月22日
簿偌 2023年10月22日
扫码二维码
获取最新动态