javascript - 将更改保存到 DB MVC
问题描述
当我尝试将一些数据保存到数据库时遇到问题。我可以看到 ID 和 Date 在 JS 函数中返回了适当的值......但是,控制器类中的 Process 函数的参数仍然为空。我不知道为什么会这样。Hello Model 中也包含了一个 linq 查询,但我没有包含它,因为不需要它。
模型:
public class Hello
{
List<string> Ids { get; set; }
List<string> Dates { get; set; }
}
控制器:
[HttpPost]
public ActionResult Process(string ids, string dates)
{
Hello model = new Hello();
if (ModelState.IsValid)
{
using (db = new DB())
{
rp = new RequestProcess();
//var c = rp.getHello(model, dates);
var c = rp.getStuff();
if (c != null)
{
foreach (var i in c)
{
if (i != null)
{
ids = i.ID;
dates = i.Date.ToString();
}
db.SaveChanges();
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}
看法:
<td><input class="id" type="checkbox" id=@item.ID /></td>
<td>@Html.DisplayFor(x => @item.ID)</td>
<td><input class="date" id=date@item.ID type="text" value='@item.Date'/></td>
$(document).ready(function () {
var ids = "";
var dates = "";
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Process";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, dates: dates },
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (success === true) {
alert("HERE WE ARE");
}
else {
alert("eror");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};
任何帮助,将不胜感激!
解决方案
我认为你需要contentType: 'application/json'
在你的$.ajax({});
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json'
});
另外,尝试添加[FromBody]Hello model
您的控制器操作。
推荐阅读
- reactjs - aws amplify 将自定义域添加到存储
- google-data-studio - 为什么不能将日期导入 Google 数据洞察连接器?
- r - 使用模板将扩展文件传递给 grunt 中的外部脚本
- android - 在循环内更新 showdialog/alertdialog
- visual-studio-code - VSCode natvis 处理某些变量,但不处理相同模板类型的其他变量
- angular - 如何在组件中重用有角度的材料表标题和样式?
- html - 嵌套列高度问题 Bootstrap 5
- authentication - 试图从证书中获取访问令牌
- javascript - NideJS 使用 Winston 进行日志记录 - 如何拥有动态字段
- javascript - 状态更新后 React 组件中没有重新渲染