【问题标题】:DataTables MVC on Postback the data is nullDataTables MVC on Postback 数据为空
【发布时间】:2019-12-03 10:17:00
【问题描述】:

我最初使用 MVC 表向用户显示数据,但由于数据非常大并开始抛出 storage out of memory 异常,我决定切换到 DataTables。数据显示正常,但在回发时,没有数据传入 HTTPPost 操作方法。我知道 MVC View 有隐藏视图来存储值,并且在回发期间它们绑定模型但是我们将如何使用数据表复制这种行为?

谢谢

@model IList<ViewModels.ReferralViewModel>@model IList<ViewModels.ReferralViewModel>

@{
    Layout = "";
}

@if (Model != null)
{
    <script src="~/Scripts/DataTables/jquery.dataTables.min.js" type="text/javascript"></script>
    <script src="~/Scripts/DataTables/dataTables.bootstrap.js" type="text/javascript"></script>

    <link href="~/Content/DataTables/css/dataTables.bootstrap.css" />
    <script type="text/javascript">

        var editor;
        $('#example').DataTable({
            "serverSide": true,
            "processing": true,

            "order": [[1, 'asc']],
            "ajax": {
                "url": "/SMS/ReferralDetailsTest",
                "type": "POST",
                "dataType": "json"
            },
            'columnDefs': [{
                'targets': 0,
                'searchable': false,
                'orderable': false,
                'className': 'dt-body-center',
                'render': function (data, type, full, meta) {
                    return '<input type="checkbox" name="IsSelected[]">';
                }
            },
                {
                    'targets': 17,
                    'data': null,
                    'defaultContent': "<input type=\"text\" size=\"100\" style = \"width: 95px; padding: 6px 2px 6px 2px\" >"
                },
                {
                    'targets': 19,
                    'data': null,
                    'defaultContent': "<input type=\"button\" value=\"SMS\" class=\"btn btn - primary\" onclick=\"return $('#sendSMS').click();\" />"
                }
            ],
            "columns": [
                {
                    "data": null,
                    "defaultContent": '',
                    "className": 'select-checkbox',
                    "orderable": false,
                    "title": "Select All"
                },
                { "title": "Referral Id", "data": "ReferralId", "autoWidth": true },
                { "title": "First Name", "data": "patient.PatientFirstName", "autoWidth": true },
                { "title": "Last Name", "data": "patient.PatientLastName", "autoWidth": true },
                { "title": "Referral Date", "data": "ReferralDate", "autoWidth": true },
                { "title": "Referral Priority", "data": "ReferralPriority", "autoWidth": true },
                { "title": "Referral HospCode", "data": "ReferralHospCode", "autoWidth": true },
                { "title": "Referral Specialty Code", "data": "ReferralSpecialtyCode", "autoWidth": true },
                { "title": "Referral Specialty Name", "data": "ReferralSpecialtyName", "autoWidth": true },
                { "title": "Referral Clinic Code", "data": "ReferralClinicCode", "autoWidth": true },
                { "title": "Referral Clinic Description", "data": "ReferralClinicDescription", "autoWidth": true },
                { "title": "Last Booked Clinic Category Code", "data": "LastBookedClinicCategoryCode", "autoWidth": true },
                { "title": "Last Booked Clinic Category", "data": "LastBookedClinicCategory", "autoWidth": true },
                { "title": "Last Booked Clinic Code", "data": "LastBookedClinicCode", "autoWidth": true },
                { "title": "Last Booked Clinic Description", "data": "LastBookedClinicDescription", "autoWidth": true },
                { "title": "Mobile No", "data": "patient.MobileNumber", "autoWidth": true },
                { "title": "Overwrite Mobile No", "data": null },
                { "title": "Status", "data": "Status", "autoWidth": true }
            ],

            "select": {
                "style": 'os',
                "selector": 'td:first-child'
            }
        });
    </script>


    <div class="form-group">
        &nbsp;
    </div>
    <div>
        <ul class="nav nav-tabs" role="tablist" id="DetailsTab">
            <li role="presentation" class="active"><a href="#Referral" aria-controls="Referral" role="tab" data-toggle="tab" class="tbs">Referrals</a></li>
            <li role="presentation"><a href="#Responses" aria-controls="Response" role="tab" data-toggle="tab" class="tbs">Responses</a></li>

        </ul>
        <div class="tab-content">

            <div role="tabpanel" class="tab-pane active" id="Referral">
                <br />


            </div>

            <div>
                <table class="table table-striped" id="example"></table>


            </div>
        </div>
    </div>
}

--post方法代码--

      $('#sendSMS').click(function () {
     var formData = $('#sendSMSForm').serialize();
                    $.ajax({
                        type: "POST",
                        url: "/SMS/SendSMSForClients",
                        data: formData, //if you need to post Model data, use this
                        success: function (result) {
                            $("#partial").html("");
                            $("#partial").html(result);

                            searchReferrals(referralSpecialty, referralClinicName, referralClinicCode, referralPriority, referralStartDate, referralEndDate);
                            $('.nav-tabs a[href="#patientsReferral"]').tab('show');
                            $('.tab-pane a[href="#patientsReferral"]').tab('show');
                            $("#loading").hide();
                        },
                         error: function (jqXHR, textStatus, errorThrown) {
                            $("#partial").html("");
                            $('#partial').html('<p>status code: ' + jqXHR.status + '</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>' + jqXHR.responseText + '</div>');
                            console.log('jqXHR:');
                            console.log(jqXHR);
                            console.log('textStatus:');
                            console.log(textStatus);
                            console.log('errorThrown:');
                             console.log(errorThrown);

                        },
                    });

}

【问题讨论】:

  • 当您在数据表中呈现列表时,您需要使用索引呈现每个输入 - 请参阅此问题以将值列表发布到控制器 (stackoverflow.com/questions/27925865/…)
  • 第二点是我们看不到 Form 元素 - 查看 @Html.BeginForm() - MVC 模型绑定器将绑定 Form 元素内的数据(也没有提交按钮 - 你怎么POST 数据到服务器)?
  • 嗨@Baahubali,能否请您提供 Post Action 方法的代码?

标签: c# model-view-controller datatables datatables-1.10


【解决方案1】:

我认为您可能仍在考虑 Webforms 和 ViewState。 使用网络表单,您可以将数据加载到对象中,然后该数据存储在隐藏的输入中,并通过表单发布 (PostBack) 发送回服务器。

但是 MVC 不保留状态。因此,即使在发布表单之后,您也需要再次从数据库重新加载所有数据并将其发送到模型。否则该对象将为空。

网络表单

protected void Page_Load(object sender, EventArgs e)
{
    //load the data from a source
    DataTable dt = LoadFromDB();

    if (!IsPostBack)
    {
        //bind data to an object
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    //do stuff here on form post (PostBack)

    //you don't have to rebind data to GridView1 here since the data is retained in ViewState 
}

MVC

public ActionResult Index()
{
    var model = new MyModel();

    //load the data from a source
    model.dt = LoadFromDB();

    return View(model);
}

[HttpPost]
public ActionResult Index(MyModel model)
{
    //do stuff here on form post

    //load the data again since it is not retained in a ViewSate
    //if you do not then dt will be null
    model.dt = LoadFromDB();

    return View(model);
}

附带说明一下,如果您的数据集太大而引发内存异常,您可能需要处理某种形式的分页,而不是将所有数据转储到客户端。

【讨论】:

  • 可能我不清楚,但在您调用 LoadFromDB() 函数之前,您正在从 Post 或提交接收 MyModel 对象,这是我所追求的并且始终为空。
  • 这就是我想说的。它是空的,因为它不是通过 PostBack 发送的。只有绑定到属性的输入控件才会发送到服务器,通常像这样@Html.TextBoxFor(model =&gt; model.Email)。这就是您需要再次加载数据的原因。
  • 是的,但是在数据表中,我有一个复选框和一个文本框的输入类型,我需要回发这两个字段。但是,它们都以 null 的形式出现。
  • 如果您自己创建这些输入,我想您可以使用 Request.Form 获取值
  • 如果您看到我的问题,我已经提供了包含输入元素的代码。在回发期间,request.form 中没有数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-21
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多