【问题标题】:MVC3 Ajax Get String and post it backMVC3 Ajax 获取字符串并将其回传
【发布时间】:2011-04-11 09:31:33
【问题描述】:

在 MVC3 页面加载时,我在模型中有一个字符串,它应该是 JSONObj。

private string CreateJSONObj(Model model)
{ return "{ name: 'test', Items: [{ test: 1 }, { test: 2 }]"; }

Model.jsonModel = CreateJSONObj(model);

现在我想在我的页面中实现它:

<script>var jsModel = eval('@Model.jsonModel');

var jsonModel = $.toJSON(jsModel);
$.ajax({
        url: 'Page/SetJSON/',
        type: "POST",
        data: jsonModel,
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            $('#test').html('Saved').fadeIn(),
        },
        error: function () {
            $("#test").html("error"),
        }
        });</script>

但是控制器得到一个空对象。如果我将 jsonstring 写入脚本,一切都很好。

我应该使用 eval 吗?但是 var jsModel = eval('@Model.jsonModel');没有效果。怎么了? :-)

【问题讨论】:

    标签: ajax json asp.net-mvc-3 get


    【解决方案1】:

    您不需要在模型上使用CreateJSONObj 方法或jsonModel 属性。为了在视图中使用它,您可以简单地使用 JavaScriptSerializer 类,它将服务器端模型对象转换为 javascript 对象:

    <script type="text/javascript">
        var jsModel = @Html.Raw(new JavaScriptSerializer().Serialize(Model));
        $.ajax({
            url: '@Url.Action("SetJSON", "Page")',
            type: 'POST',
            data: JSON.stringify(jsModel),
            contentType: 'application/json; charset=utf-8',
            success: function () {
                $('#test').html('Saved').fadeIn();
            },
            error: function () {
                $('#test').html('error');
            }
        });
    </script>
    

    这将成功地将模型发送到以下控制器操作:

    [HttpPost]
    public ActionResult SetJSON(Model model)
    {
        ...
    }
    

    Model 类包含所有必要信息:

    public class Model
    {
        public string Name { get; set; }
        public IEnumerable<Item> Items { get; set; }
    }
    
    public class Item
    {
        public int Test { get; set; }
    }
    

    和控制器:

    public class PageController: Controller
    {
        // Used to render the view
        public class Index()
        {
            var model = new Model
            {
                Name = "Test",
                Items = new[]
                {
                    new Item { Test = 1 },
                    new Item { Test = 2 },
                }
            };    
            return View(model);
        }
    
        // Used to handle the AJAX POST request
        [HttpPost]
        public ActionResult SetJSON(Model model)
        {
            ...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多