-5

假设我有一个返回 JsonResult 的操作。就像下面的代码:

 public ActionResult testAction()
        {

            return Json(new { name="mike",age="20"});

        }

它 json 一个匿名对象并返回它。然后我想用剃刀引擎在 View (.cshtml) 文件中编写下面的代码。

@{
 JsonResult m = ///some method can help me get the JsonResult
 //Then I can print the value of m
 @m.Data.ToString()

}

怎么做?

4

4 回答 4

1

为什么在视图中使用 json 结果?你可以:

public ActionResult testAction()
        {

            return View(new Model{ name="mike",age="20"});

        }
于 2013-10-16T07:31:20.633 回答
0

在您的视图中,您可以testAction通过 Ajax 调用调用您的方法,然后访问您返回的对象。但据我所知,你必须返回一个模型。

创建模型

public class YourModel
{
    public string Name { get; set; }
    public int Age { get; set; }
}

控制器:

public ActionResult testAction(string name, int age)
    {
        YourModel ym = new YourModel();
        ym.Name = name;
        ym.Age = age;

        return Json(ym, JsonRequestBehavior.AllowGet);

    }

您的看法:

var name = "Mike";
var age  = "20";

$.ajax({
        url         :    "@Url.Action("testAction", "YourController")",
        contentType :    "application/json; charset=utf-8",
        dataType    :    "json",
        type        :    "POST",
        data        :    JSON.stringify({name: name, age: age})
    }).done(function (data) {
        alert(data); // Do what you want with your object, like data.Name
    })

这是一个虚拟示例,因为您将参数从视图传递到控制器,然后将它们发送回视图,但我认为此示例可以帮助您更好地了解如何在 ASP.NET MVC3 中使用 Ajax 调用。Ajax 调用是异步的,但是感谢deferred .done,您等待服务器调用结束以确保您的data对象被填充

于 2013-10-16T07:39:48.657 回答
0

你必须使用ajax来阅读。

$.ajax({
    url: "/YourController/testAction/",
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: json,
    type: 'POST',
    success: function (data) {
        setTimeout(function () {
             //find your html element and show.
             $("#ShowSomewhere").val(data.name);

        }, 500);
    },
    error: function (jqXHR, textStatus, errorThrown) {
    }
});
于 2013-10-16T07:43:50.810 回答
0

尝试使用 Html.Action("actionName");
这返回一个字符串

于 2013-10-22T02:21:40.610 回答