【问题标题】:return json object as a string in asp.net MVC在 asp.net MVC 中将 json 对象作为字符串返回
【发布时间】:2013-09-06 02:33:33
【问题描述】:

我正在尝试从我的视图中进行 ajax 调用,从我的控制器返回一个 json 对象。但是,当我尝试这个时,我得到了对象类型,而不是字符串形式的值。这是我的代码..

控制器

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult GetPerson()
    {
        var _model = _person;
        return Json(_model, JsonRequestBehavior.AllowGet);
    }

    static Person _person = new Person()
    {
        FirstName = "Steve",
        LastName = "Johnson",
        Age = 27
    };  
}

查看

@{
Layout = null;
}

<!DOCTYPE html>

<html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <script src="~/Scripts/jquery-2.0.3.min.js"></script>
    </head>
    <body>
        <div>
            <form>
                <fieldset>
                    <legend>The Person</legend>
                    <label>Name: </label>
                    <input />
                    <label>Age: </label>

                </fieldset>

            </form>
        </div>
    <script type="text/javascript">
        $(document).ready(function() {
            $.ajax({
            url: '/Home/GetPerson',
            type: 'GET',
            success: function (result) { alert(result);}
        });
    });
    </script>

警告框返回[object Object]。我正在尝试获取“Person”对象的字符串值。

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: c# ajax asp.net-mvc razor-2


    【解决方案1】:

    你没有从你 ddet 的警报中获取数据来指定你试图提醒的变量

     success: function (result) { alert(result.FirstName);}
    

    【讨论】:

      【解决方案2】:

      success: function (result) { alert(result[0].FirstName);} 当返回一个 json 结果值时,你应该在字段名后面加上索引号

      【讨论】:

      • 在他的例子中,结果将是一个对象,而不是一个数组。
      • 这样是获取结果中第一个Firstname的值。
      【解决方案3】:

      尝试将 alert(result); 更改为 alert(JSON.stringify(result); 这样您就可以看到实际返回的 JSON 字符串。

      【讨论】:

        猜你喜欢
        • 2015-10-24
        • 2010-12-04
        • 1970-01-01
        • 1970-01-01
        • 2014-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多