javascript - asp.net mvc serialize() 在 Controller 的模型中返回空

标签 javascript c# jquery asp.net asp.net-mvc

我的cshtml片段:

@model Models.ClockingInformationViewModel
<form id="clocking-form">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="control-label">Time in</label>
                            <div class="input-group date form_datetime">
                                @Html.TextBoxFor(m => m.Attendance.Time01In, new { @class = "form-control", @readonly = "readonly", size = "16" })

                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="control-label">Job code</label>
                            @Html.TextBoxFor(m => m.Attendance.Time01InJob, new { @class = "form-control" })

Controller :

[HttpPost]
public JsonResult ClockingInformation(ClockingInformationViewModel model)
{
    return null;
}

View 模型:

public class ClockingInformationViewModel
{
    public Attendance Attendance { get; set; }
    public List<Clock> ClockingLocations { get; set; }
}

在我的 JavaScript 中,我有这个:

function saveClockingInformation() {
    var data = $("#clocking-form").serialize();
    $.post($("#clocking-info-url").val(), { model: data });
}

当我在 Controller 中设置断点时,ClockingInformationViewModel model 属性为 null。

当我使用 serializeArray() 而不是 serialize() 时,ClockingInformationViewModel model 不为 null,但属性 Attendance 是。

我确信这是我忽略的一些愚蠢错误。

有什么见解吗?

最佳答案

您的 var data = $("#clocking-form").serialize(); 代码行已经将您的表单序列化为对象,因此代码需要是

function saveClockingInformation() {
    var data = $("#clocking-form").serialize();
    $.post($("#clocking-info-url").val(), data);
}

发送表单数据为

Attendance.Time01In=someValue&Attendance.Time01InJob=anotherValue

而您当前使用 { model: data } 的实现将表单数据发送为

model[Attendance.Time01In]=someValue&model[Attendance.Time01InJob]=anotherValue

与您的模型没有关系,因此绑定(bind)失败。

旁注:您使用 $("#clocking-info-url").val() 建议您将 URL 放入隐藏输入中。相反,使用

var url = '@Url.Action("yourAction", "yourController")',
$.post($(url, data);

或者,如果您使用 Html.BeginForm() 生成了表单,则使用

var form = $("#clocking-form");
var url = form.attr('action');
$.post($(url, data);

关于javascript - asp.net mvc serialize() 在 Controller 的模型中返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35571341/

相关文章:

javascript - 循环遍历对象的嵌套数组

javascript - 将 JavaScript 函数编译成可调用的 Java 对象?

javascript - 如何分离两个 jQuery 函数

javascript - AJAX Post 使用 Python 和 javascript 存储 JSON

javascript - 无法在 Bixby 工作室中使用 for ... of ?

C# 文本对齐

c# - 按类型名称从 StructureMap 获取实例

c# - 使用前设置 StringBuilder?

javascript - 如何在Jquery中迭代Table来更改内容

javascript - 在加载时执行匿名函数,然后使用 setTimeout 每 30 秒再次执行一次