MVC3 Ajax获取String并将其发回

San*_*and 0 ajax json get asp.net-mvc-3

在MVC3页面加载我有一个模型中的字符串应该是JSONObj.

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

Model.jsonModel = CreateJSONObj(model);
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

但Controller获取一个null对象.如果我将jsonstring写入脚本everthing是好的.

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

Dar*_*rov 5

您不需要在模型上使用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>
Run Code Online (Sandbox Code Playgroud)

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

[HttpPost]
public ActionResult SetJSON(Model model)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

其中Model类包含所有必要的信息:

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

public class Item
{
    public int Test { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和控制器:

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)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)