返回 JSON 或部分 html 的 ASP.NET MVC 控制器操作 [英] ASP.NET MVC controller actions that return JSON or partial html

查看:20
本文介绍了返回 JSON 或部分 html 的 ASP.NET MVC 控制器操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建控制器操作,该操作将根据参数返回 JSON 或部分 html.将结果异步返回到 MVC 页面的最佳方法是什么?

I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?

推荐答案

在您的操作方法中,返回 Json(object) 以将 JSON 返回到您的页面.

In your action method, return Json(object) to return JSON to your page.

public ActionResult SomeActionMethod() {
  return Json(new {foo="bar", baz="Blech"});
}

然后只需使用 Ajax 调用 action 方法即可.您可以使用 ViewPage 中的一种辅助方法,例如

Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as

<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>

SomeMethod 将是一个 javascript 方法,然后评估返回的 Json 对象.

SomeMethod would be a javascript method that then evaluates the Json object returned.

如果你想返回一个普通的字符串,你可以只使用 ContentResult:

If you want to return a plain string, you can just use the ContentResult:

public ActionResult SomeActionMethod() {
    return Content("hello world!");
}

ContentResult 默认返回一个 text/plain 作为它的 contentType.
这是可重载的,因此您也可以这样做:

ContentResult by default returns a text/plain as its contentType.
This is overloadable so you can also do:

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");

这篇关于返回 JSON 或部分 html 的 ASP.NET MVC 控制器操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆