【问题标题】:Can I submit razor form data with jQuery Submit我可以使用 jQuery Submit 提交 Razor 表单数据吗
【发布时间】:2018-02-01 09:42:40
【问题描述】:

我有一个剃刀视图,它在 Get 调用 Controller 时呈现,

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            <div>
                @Html.LabelFor(model => model.StartTime, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-2">
                    @Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.StartTime, "", new { @class = "text-danger" })
                </div>
            </div>
            <div>
                @Html.LabelFor(model => model.EndTime, htmlAttributes: new { @class = "control-label col-md-1" })
                <div class="col-md-2">
                    @Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.EndTime, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.SampleTimes, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-2">
                @Html.DropDownListFor(model => model.SelectedSampleTime, Model.SampleTimes, htmlAttributes: new { @class = "selectpicker form-control", @data_actions_box = "true" })
                @Html.ValidationMessageFor(model => model.SelectedSampleTime, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Measurands, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-2">
                @Html.DropDownListFor(model => model.SelectedMesurands, Model.Measurands, htmlAttributes: new { @class = "selectpicker form-control", @multiple = "", @data_actions_box = "true" })
                @Html.ValidationMessageFor(model => model.SelectedMesurands, "", new { @class = "text-danger" })

            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Customers, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-2">
                @Html.DropDownListFor(model => model.SelectedCustomers, Model.Customers, htmlAttributes: new { @class = "selectpicker form-control", @multiple = "", @data_actions_box = "true" })
            </div>
        </div>
           <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                @*<input value="Run Report" class="btn btn-default" id="btnRunReport" type="submit" data-toggle="modal" data-target="#reportModal" />*@
                <input value="Run Report" class="btn btn-default" id="btnRunReport" />
            </div>
        </div>
    @Html.Partial("_reportsModal")
}

在同一个控制器中,我有一个索引帖子,

[HttpPost]
        public JsonResult Index(ReportViewModel vm)
        {

            List<MultiStoredProcedureReturnData> listSpData = new List<MultiStoredProcedureReturnData>();

            List<Chart> chartList = new List<Chart>();

            if (ModelState.IsValid)
            {
                Chart chartData = new Chart();

                string sleectedMeasurandName = "";
                foreach (var item in vm.SelectedMesurands)
                {

                    listSpData.Add(new MultiStoredProcedureReturnData());
                   //Some more updates

                    chartData = UpdateChart();
                    chartList.Add(chartData);
                }

            }


            return Json(chartList);
        }

现在,我想在单击按钮时调用此方法,但它不能, 因为它会将 json 数据返回给浏览器。

相反,我想使用 jQuery click event ,使用 Post 获取所有 JsonData,然后从返回数据更新 Index 页面上的图表并显示在模态上。

我尝试执行以下操作,但正如预期的那样,我丢失了所有模型绑定。有没有办法使用 jQuery 而不会丢失数据。我可以继续从每个元素中获取值,然后创建一个发布请求。但是使用现有的模型绑定并取回数据会更好!

 $('#btnRunReport').click(function (e) {
                e.preventDefault();
                $.ajax({
                    type: "POST",
                    url:"Reports/Index",
                    success: function (result) { console.log(result); }
                });
            });

【问题讨论】:

  • 只需添加data: $('form').serialize() 即可回发表单值。但是您确实应该处理表单 .submit() 事件(不是按钮事件)并在进行 ajax 调用之前检查表单是否有效(如果不是则取消调用)
  • 那么,点击按钮触发表单提交?

标签: javascript jquery asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

要序列化表单控件,您可以使用$('form').serialize();

但是,您应该处理表单提交事件而不是按钮单击事件,以便触发客户端验证并且您可以测试数据是否有效

$('form').submit(function(e) { // consider giving your form an id attribute and using that as the selector
    if (!$(this).valid()) {
        return; // cancel and display validation errors   
    }
    var formData = $(this).serialize();
    $.ajax({
        url: '@Url.Action("Index", "Reports")', // always use `Url.Action()
        type: "POST",
        data: formData,
        success: function (result) {
            ....
        }
    });
    return false; // this is just an alternative to using e.preventDefault
}

【讨论】:

  • 非常感谢,我担心如何在没有模型投标的情况下提交这么多值,因为从每个元素中获取值是麻烦和难以维护的。再次感谢!
  • 您的视图还有另一个问题。您在视图中的foreach (var item in vm.SelectedMesurands) 表示SelectedMesurandsIEnumerable,这意味着您必须使用ListBoxFor(),而不是DropDownListFor() - 请参阅Why does the DropDownListFor lose the multiple selection after Submit but the ListBoxFor doesn't?
  • SelectedCustomers 属性同上
  • 将改变这一点,因为这是一种更好的方法。我确实参考了链接,但我正在使用 Fordropdown 将所选项目的集合返回到我的控制器中!
  • 是的,但你不能一开始就设置它(即从控制器到视图的绑定不起作用 - 如果在 GET 方法中将SelectedMesurands 设置为包含[1, 4] 的数组,则视图中不会选择值为 1 和 4 的选项
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
相关资源
最近更新 更多