javascript - Ajax POST 和 Stringify 混淆

标签 javascript jquery ajax asp.net-mvc

我正在学习使用 Ajax 进行 POST,我注意到很多在静态数组上使用 stringify 的示例。

在我的示例中,我通过从 <input> 中提取的 jQuery 对象构建数组值(value)观。

查询

    function PostEdit(vData){
        var content = JSON.stringify(vData); //content = "[{"Id":"1","Date":"7/12/2017 12:00:00 AM"}]"

            $.ajax({
                url: '@Url.Action("Index", "PostViewData")',
                type: "POST",
                data: JSON.stringify({ ViewData : vData }),
                contentType: "application/json",
                success: function (result) {
                    alert("success" + result);
                },
                error: function (result) {
                    alert("failure" + result);
                }
        });
        return;
    }

Controller

    [HttpPost]
    public ActionResult Index(List<DataViewModel> ViewData )
    {
        if(ViewData != null)
        {
            var json = new { success = true };
            return Json(json);
        }
        return Json(false);
    }

View 模型

public class DataViewModel
{
    public DataViewModel(string id, string date)
    {
        Id = id;
        Date = date;
    }
    public string Id { get; set; }
    public string Date { get; set; }
}

在哪里DataViewModel是一个由两个值组成的类,Id , 和 Date对应于我的 JS 对象。

vData将函数作为值 vData = [Object] 输入, 当我调用 .stringify(vData)它返回 content = "[{"Id":"1","Date":"7/12/2017 12:00:00 AM"}]"

content 的值以上是我看到的大多数示例在 stringify 之前的结构,例如示例 here .

一旦采用这种格式,大多数响应、示例都会调用 stringify。

现在当我调用 .stringify(ViewData : vData)我什至没有到达 Controller 。 Ajax 无法发布。相反,当我调用 .stringify(ViewData : content) ,我将其发送到 Controller ,但值为空。我错过了什么/误解了什么?

我正在寻找关于 Ajax Post 和 Stringify 的更好解释,以及它如何与 Controller 参数交互。

最佳答案

只需将无参数构造函数添加到您的模型中。通过该更改,您的代码将按原样运行。 ASP 无法将您的 json 解析为 DataViewModel,因为它试图调用不存在的默认构造函数。

public class DataViewModel
{
    public DataViewModel()
    {

    }
    //...other methods and members here
}

关于javascript - Ajax POST 和 Stringify 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45064377/

相关文章:

javascript - 捕获重定向下载链接的 HTTP 状态 300

JavaScript 跨浏览器 : Is it safe to treat a string as array?

javascript - React JS 访问嵌套在状态中的数组

javascript - JQuery 错误 : cannot call methods on dialog prior to initialization; attempted to call method 'close'

jquery - 奇怪的 CSS/图像问题

php - Bootstrap : active class

jquery - 同时使用 jQuery 和 FormEncode 验证表单而不重复

javascript - 使用 ExtJS MVC 构建 UI 的好教程/插件

javascript - JSONP 在 Chrome 中工作,但在 Firefox/IE 中不起作用?

javascript - 检查 Cookie ; load() 如果cookie匹配,需要重新加载才能看到新内容