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

查看:158
本文介绍了返回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(对象)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只需调用操作方法。你可以使用从的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天全站免登陆