【问题标题】:Submit Form with Data Model and Get JSON Reply使用数据模型提交表单并获取 JSON 回复
【发布时间】:2020-03-24 17:16:36
【问题描述】:

我在剃刀视图中有一个表单,其定义如下:

using (Html.BeginForm("Submit", "CT0, FormMethod.Post, new { id = "rForm" }))

我在 CT0 中有一个名为 submit 的方法,它接受一个模型:

public async System.Threading.Tasks.Task<ActionResult> Submit(CTModel ctmodel)

当我像这样提交表单时,它会使用正确的模型命中函数,但我无法获得 JSON 响应:

var form = document.getElementById('rForm');
form.submit();

我试过ajax,但是它没有提交给控制器,还是报错,还是成功。它似乎什么也没做:

         $("#rForm").submit(function (e) {

            e.preventDefault(); // avoid to execute the actual submit of the form.

            var form = $(this);
            var url = form.attr('action');

            $.ajax({
                type: "POST",
                url: url,
                data: form.serialize(), // serializes the form's elements.
                success: function (data) {
                    alert(data); // show response from the php script.
                }
            });


        });

我试过 jquery,但它从来没有点击控制器中的提交功能或错误输出。它似乎什么都不做:

        $(function () {
            $('form[name=rForm]').submit(function () {
                $.post($(this).attr('action'), $(this).serialize(), function (json) {
                    alert(json);
                }, 'json');
                return false;
            });
        });

那么,对于我如何提交表单、使用模型并获得响应有什么想法吗? 提前致谢。

【问题讨论】:

    标签: jquery ajax razor


    【解决方案1】:

    这行得通:

            var form = $("#rForm");
            $.ajax({
                type: 'POST',
                url: "/CT0/Submit",
                data: form.serialize(),
                success: function (data) {
                    showModal("Error Getting Address: " + data.message);
                },
                error: function (xhr) {
                    showModal("Error Getting Address: " + xhr.status + " " + xhr.statusText);
                }
            })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      相关资源
      最近更新 更多