javascript - ASP.NET mcv : How to send javascript array to c# controller

标签 javascript c# asp.net-mvc controller

我有这个 javascript 数组:

formatData = {
                            title: title,
                            start: startFormat,
                            end: endFormat
                        };

我想将 formatData 发送到 C# Controller 的方法(并将其作为数组接收以发布到数据库):

//HomeController.cs
public ActionResult setReservation()
    {
        Database db = new Database();
        db.setReservations(reservation);
        return View();
    }

我尝试使用以下 AJAX 代码发送 javascript 数组:

$.ajax({
                            url: '/Controller/HomeController',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify({
                                formatData: formatData
                            }),

                        });

没有成功。浏览器“网络”选项卡显示 404。我做错了什么?如何从服务器端 c# Controller 中的客户端 javascript 捕获数组作为类似 C# 数组的形式?如何将 AJAX 帖子附加到 c# Controller 中的 setReservation 方法?

提前非常感谢。

编辑:formatData 应传递给 Controller ​​(HomeController.cs)。在 Controller 中,formData(title, start, end)中的数据必须传递给另一个类(Database)的对象(db)的方法(setReservations),其中数据将被注入(inject)到sql查询字符串中。

最佳答案

首先,您的 AJAX 方法中的 URL 是错误的。尝试这样的事情:

$.ajax({
                        url: '/Home/SetReservation',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            formatData: formatData
                        }),

                    });

然后,在 Controller 中,您需要将该列表作为要使用的操作的参数。另外,将操作标记为 [HttpPost]:

[HttpPost]
public ActionResult SetReservation([FromBody]Reservation reservation)
    {
        Database db = new Database();
        db.setReservation(reservation);
        return View(); // you might want to redirect to another view instead
    }

关于javascript - ASP.NET mcv : How to send javascript array to c# controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670450/

相关文章:

c# - 在 C# 中编写以下函数的更短方法?

c# - ASP.NET MVC3 Entity Framework - 指定为此 MSL 一部分的 EntitySet 'x' 在 MetadataWorkspace 中不存在

javascript - 使用 Datejs - 获取星期几

php - memcache php 缓存 js css 和图像

javascript - 使用 window.open(<url>,'_self) 时收到警告资源解释为文档但使用 MIME 类型 application/octet-stream 传输

asp.net-mvc - 修改后如何在继承自 DefaultModelBinder 的自定义模型 Binder 中重新验证我的模型?

c# - 什么可以破坏一个 session 对象asp .net?

javascript - 将 0 转换为 0.00 作为数字

c# - 如何强制 Sgen 创建 .net 3.5 序列化程序集

c# - 获取 Silverlight 5 部署路径(在浏览器中以完全信任模式运行时)