我正在尝试创建控制器操作,该操作将根据参数返回 JSON 或部分 html。将结果异步返回到 MVC 页面的最佳方法是什么?
在您的操作方法中,返回 Json(object) 以将 JSON 返回到您的页面。
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
然后只需使用 Ajax 调用操作方法即可。您可以使用 ViewPage 中的辅助方法之一,例如
<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
SomeMethod 是一个 JavaScript 方法,然后评估返回的 Json 对象。
如果你想返回一个纯字符串,你可以使用ContentResult:
public ActionResult SomeActionMethod() {
return Content("hello world!");
}
ContentResult 默认返回 text/plain 作为其 contentType。
这是可重载的,所以你也可以这样做:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)