通过AJAX将JSON引入我的控制器:我缺少什么?

时间:2015-06-12 00:14:46

标签: c# asp.net ajax json asp.net-mvc

我有

    // fbi: Files batch info

    $.ajax({
        xhr: function() {
            var xhr = new window.XMLHttpRequest();
            return xhr;
        },
        type: 'POST',
        url: '@Url.Action("AddFilesToDB","FileUploadAsync")',
        data:  JSON.stringify(fbi),
        contentType: false,
        processData: false,
        success: function(retInfo) {
            console.log(JSON.stringify(retInfo));
        }
    });

如何引用JSON.stringify的结果,像

这样的对象
'{org:"someOrganization",cat:"someCategory",fileNames:[somepic.jpg,somepaper.docx]'

来自我的控制器

[HttpPost]
public async Task<JsonResult> addFilesToDB (???)
{
    ??? Want to use the value of data
}

我知道这可能是一个显而易见的问题,但我对这些东西不熟悉

1 个答案:

答案 0 :(得分:0)

这是解决方案,首先创建一个模型FileData

public class FileData
{
    public string org { get; set; }
    public string cat { get; set; }
    public string[] filenames { get; set; }    
}

然后创建一个动作,如下所示 -

public JsonResult PostFileData(FileData filedata)
{
     return Json("True");
}  

然后在视图中你的JQuery代码应该是 -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {
        $("#btnSubmit").click(function () {
            var roles = ["somepic.jpg", "somepaper.docx"];

            var model = new Object();
            model.fileNames = roles;
            model.cat = "business";
            model.org = "news";

            jQuery.ajax({
                type: "POST",
                url: "@Url.Action("PostFileData", "Home")",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ filedata: model }),
                success: function (data) { alert(data); },
                failure: function (errMsg) {
                    alert(errMsg);
                }
            });
        });
    });
</script>

<input type="button" value="Click" id="btnSubmit" />

当您点击btnSubmit时,所有值都会过帐到上面的操作,并且断点应该如下所示 -

enter image description here