执行$ .post时,Controller操作中的键入模型始终为null

时间:2016-04-27 08:48:12

标签: ajax asp.net-mvc model-binding

我正在尝试将一些数据发布回MVC项目中的一个操作方法。我已经有了一个不同的Ajax表单,所以我不能使用另一个Ajax表单。所以我使用$ .post函数。然后问题是,当调用我的action方法时,我的模型为null。

这是我的观点:

@model ActivityViewModel

@using (Ajax.BeginForm("Create", "Activities", new AjaxOptions() { UpdateTargetId = "panelContent", InsertionMode = InsertionMode.Replace }, new { id = "createactivity", autocomplete = "off" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(m => m.EmployeeId)
    @Html.HiddenFor(m => m.IsAbscence)
    @Html.HiddenFor(m => m.Id)
    @Html.HiddenFor(m => m.ConflictIds)
    @Html.HiddenFor(m => m.IsAbscence)

    @Html.TextBoxFor(model => model.Date, "{0:dd.MM.yyyy}", new { @type = "date", @class = "ms-TextField-field", @autocomplete = "off" })

    @if (!Model.IsAbscence)
    {
        @Html.HiddenFor(m => Model.Favorites, new { @id = "favoritehidden" })
        @Html.HiddenFor(m => Model.Archive, new { @id = "archivehidden" })

        <script type="text/javascript">
                    attachFabricCheckBoxHandler('#favoritehidden', '#favoritelabel');
                    attachFabricCheckBoxHandler('#archivehidden', '#archivelabel');
                    $(document).ready(function () {
                        $('#favoritelabel').click(function () {
                            var frm = $('#createactivity').serialize();
                            var token = $('[name=__RequestVerificationToken]').val();
                            $.post({
                                type: 'POST',
                                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                                url: '/Activities/FilterProjects/',
                                data: { __RequestVerificationToken: token, model: frm.substring(frm.indexOf("&") + 1) },
                                statusCode: {
                                    404: function (content) { showErrorDialog(content); },
                                    500: function (content) { showErrorDialog(content); }
                                },
                                success: function (data) {
                                    alert(data);
                                },
                                error: function (req, status, errorObj) {
                                    showErrorDialog(status);
                                }
                            });
                        });
                    });
        </script>

        @Html.DropDownListFor(m => m.ProjectId, new SelectList(ViewBag.Projects, "Id", "ProjectDescription"), new { @class = "ms-Dropdown-select" })
    }
    @Html.TextBoxFor(model => model.StartTime, "{0:HH:mm}", new { @readonly = "readonly", @class = "ms-TextField-field", @placeholder = "Click to choose time" })

    @Html.TextBoxFor(model => model.EndTime, "{0:HH:mm}", new { @readonly = "readonly", @class = "ms-TextField-field", @placeholder = "Click to choose time" })

    @Html.TextAreaFor(model => model.Description, new { @class = "ms-TextField-field", @style = "height:100px; resize:vertical;" })

    @if (!Model.IsAbscence)
    {
        @Html.TextAreaFor(model => model.Comment, new { @class = "ms-TextField-field", @style = "height:100px; resize:vertical;" })
    }
}

注意我删除了所有不必要的HTML,结构基本相同。这是我的ViewModel:

public class ActivityViewModel
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public string Description { get; set; }
    public int EmployeeId { get; set; }
    public string ConflictIds { get; set; }
    public string Comment { get; set; }
    public int ProjectId { get; set; }

    public bool IsAbscence { get; set; }

    public bool Archive { get; set; }

    public bool Favorites { get; set; }
}

当我使用它时,我总是在我的动作方法中得到null:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FilterProjects(ActivityViewModel model)
{            
    //When 'object model' is being passed, the serialized string and all the properties are there...
    return PartialView("Create");
}

奇怪的是,当我将一个对象而不是我输入的ViewModel传递给我的action方法时,我得到了包含所有属性的序列化字符串:

EmployeeId=1&
IsAbscence=False&
Id=0&
ConflictIds=&
IsAbscence=False&
Date=27.04.2016&
Favorites=True&
Archive=False&
ProjectId=1&
StartTime=10%3A25& //Maybe these two values are screwing up the model?
EndTime=11%3A25&
Description=&
Comment=&

我可以从这个字符串中重新实例化我的viewmodel但是如果我把我的打字模型传递给我的动作会更好。如何正确地序列化表单,以便在调用操作时它不为空?我试图忽略&#34; StartTime&#34;和&#34; EndTime&#34;属性和我删除验证令牌字符串,因为我认为他们在这里干扰,但显然这没有工作。

1 个答案:

答案 0 :(得分:0)

序列化表单时,将包含AntiForgeryToken。尝试发送表单而不指定__RequestVerificationToken

$('#favoritelabel').click(function () {
    var frm = $('#createactivity').serialize();

    $.post('/Activities/FilterProjects/', frm, function (data) {
    }).fail(function (xhr, status, errorThrown) {
        showErrorDialog(status);
    });
});