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?

推荐答案

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中的一个助手方法,例如

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

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

如果要返回普通字符串,可以使用ContentResult:

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

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相关问答推荐

如何在JMESPath中区分空和假?

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

Oracle plsql:如何将json文件加载到嵌套表中

JQ-JSON将键转换为对象

使用JQ在数组中 Select 第一个具有匹配项的项

如何在Swift中使用JSON编码器的泛型

go 语言中的 JSON 到 XML

匹配来自不同数组的值

Jolt 规范将父对象中的所有键应用于数组中的所有对象

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

如何在循环中传递列表(会话(字符串属性))以在 Gatling Scala 中创建批量 Json 请求

提交后使用 Rails 7 结合 JSON 标签进行标记

根据数据框中的其他列值将列表 json 对象插入行

如何将从嵌套 Select 返回的空值转换为空数组?

在PowerShell中按时间戳过滤JSON

在 JSON API Wordpress 上启用 CORS

JSON.NET JsonConvert 与 .NET JavaScriptSerializer

有 Json 标签但未导出

如何在 JAVA 中对 JSONArray 进行排序

使用 JSONArray 和 JSONObject 进行 Foreach