简体   繁体   English

带有Ajax帖子的空模型

[英]Null model with ajax post

I am trying to pass a model to the controller using an ajax post, but every time I do so, the model is null and I lose all the data I am trying to persist. 我试图使用ajax发布将模型传递给控制器​​,但是每次这样做,模型都是空的,并且我丢失了所有要保留的数据。

The ajax call: Ajax调用:

$('#next').click(function (e) {
    e.preventDefault();
    var url = '@Url.Action("Manage")'
    var _model = JSON.stringify(@Html.Raw(Json.Encode(Model)));
    var _page = @(Model.pager.CurrentPage + 1);

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: url,
        data: JSON.stringify({ 'model': _model, 'page': _page }),
        success: function(result) {
            console.log(result);
        }
    });
});

When I look at the serialized object, it looks like a correctly formatted JSON object with no errors thrown in the developer console. 当我查看序列化的对象时,它看起来像是格式正确的JSON对象,在开发人员控制台中没有引发任何错误。

The link that is triggering this jQuery call is just a basic action link: 触发此jQuery调用的链接只是一个基本操作链接:

@Html.ActionLink(">", "Manage", "Announcements", null, new { id = "next" })

My model is a little more complicated... 我的模型有点复杂...

public class ManageViewModel : IEnumerable<EditViewModel>
{
    [Display(Name="Start Date")]
    [DataType(DataType.DateTime)]
    public DateTime? StartDate { get; set; }

    [Display(Name="End Date")]
    [DataType(DataType.DateTime)]
    public DateTime? EndDate { get; set; }

    public string SearchString { get; set; }

    public Pager pager { get; set; }

    public List<EditViewModel> Data { get; set; }
    public List<CategoryViewModel> Categories { get; set; }

    public ManageViewModel()
    {
        Data = new List<EditViewModel>();
        Categories = new List<CategoryViewModel>();
    }

    public IEnumerator<EditViewModel> GetEnumerator()
    {
        return Data.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return Data.GetEnumerator();
    }
}

public class Pager
{
    public int TotalItems { get; private set; }
    public int CurrentPage { get; private set; }
    public int PageSize { get; private set; }
    public int TotalPages { get; private set; }
    public int StartPage { get; private set; }
    public int EndPage { get; private set; }

    public Pager(int totalItems, int? page, int pageSize = 10)
    {
        int totalPages = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
        int currentPage = page ?? 1;
        int startPage = currentPage - 5;
        int endPage = currentPage + 4;

        if(startPage <= 0)
        {
            endPage -= (startPage - 1);
            startPage = 1;
        }

        if(endPage > totalPages)
        {
            endPage = totalPages;
            if(endPage > 10)
            {
                startPage = endPage - 9;
            }
        }
        TotalItems = totalItems;
        TotalPages = totalPages;
        CurrentPage = currentPage;
        PageSize = pageSize;
        EndPage = endPage;
        StartPage = startPage;
    }
}

I can't convert the links in to a form because that breaks the pagination. 我无法将链接转换为表单,因为这会破坏分页。 Or maybe I'm just not understanding the full picture here. 也许我只是不了解这里的全部情况。

Here is the section of the View where the pagination is occurring 这是视图中发生分页的部分

if (Model.pager.EndPage > 1)
{
    <div style="color:#337AB7; padding-bottom: 0px;">Page @Model.pager.CurrentPage of @Model.pager.TotalPages</div>
    <ul class="pagination">
        @if (Model.pager.CurrentPage > 1)
        {
            <li>
                @Html.ActionLink("<<", "Manage", new { model = Model, start = Model.StartDate, end = Model.EndDate, query = Model.SearchString }, null)
            </li>
            <li>
                @Html.ActionLink("<", "Manage", new { model = Model, page = Model.pager.CurrentPage - 1, start = Model.StartDate, end = Model.EndDate, query = Model.SearchString }, null)
            </li>
        }
        @for (var _page = Model.pager.StartPage; _page < Model.pager.EndPage + 1; _page++)
        {
            <li class="@(_page == Model.pager.CurrentPage ? "active" : "")">
                @Html.ActionLink(_page.ToString(), "Manage", new { model = Model, page = _page, start = Model.StartDate, end = Model.EndDate, query = Model.SearchString }, null)
            </li>
        }
        @if (Model.pager.CurrentPage < Model.pager.TotalPages)
        {
            <li> 
                @Html.ActionLink(">", "Manage", "Announcements", null, new { id = "next" })
            </li>
            <li>
                @Html.ActionLink(">>", "Manage", new { model = Model, page = Model.pager.TotalPages, start = Model.StartDate, end = Model.EndDate, query = Model.SearchString }, null)
            </li>
        }
    </ul>
}

The action links attempting to pass the model, obviously don't work but I left them because I am focusing on getting one to work, the one listed previously, before getting all the others configured. 试图传递模型的动作链接显然不起作用,但是我离开了它们,因为我将重点放在使一个上面列出的那个起作用,然后再配置其他所有模型。

I have looked at the following SO posts and have had no luck with them: 我看过以下SO帖子,但运气不佳:
Post an MVC model with AJAX? 使用AJAX发布MVC模型?
Model properties null on Ajax post from list box change event 列表框更改事件在Ajax发布上模型属性为null
How to send a model in jQuery $.ajax() post request to MVC controller method 如何在jQuery $ .ajax()中将模型发送请求到MVC控制器方法
Pass Model To Controller using Jquery/Ajax 使用Jquery / Ajax将模型传递给控制器
How to pass model in ajax post request? 如何在ajax发布请求中传递模型?

Any ideas on how I might be able to do this? 关于如何执行此操作的任何想法? I need the model data to persist for searching/filtering which is done through a form. 我需要模型数据来持久保存以通过表单完成搜索/过滤。 Thank you in advance for taking a look and giving your insights! 预先感谢您浏览并提供您的见解!

You need to include a parameterless constructor for your models. 您需要为模型包括无参数构造函数。 From the screenshot you have sent it seems there isn't a parameterless constructor for public Pager model. 从您发送的屏幕快照来看,似乎没有公共Pager模型的无参数构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM