如何使用DataTables Ajax将整个表单提交给MVC Controller Action

时间:2022-11-23 14:24:47

I'm revisiting a problem I had early on with a page that contains quite a few input and select controls in a form. I prefer that my Controller Action uses the View Model to determine the input values, but the model's members are always empty when submitted. Here is my undesirable WORKING code, briefly:

我正在重新审视我早期遇到的一个问题,该页面包含一些表单中的输入和选择控件。我更喜欢我的Controller Action使用View Model来确定输入值,但是模型的成员在提交时总是为空。这是我不受欢迎的工作代码,简要说明:

VIEW MODEL:

public class MyViewModel
{
    [Display(Name = "Project Name")]
    public string ProjectName { get; set; }

    [Display(Name = "Project Country")]
    public string ProjectCountry { get; set; }
    public IEnumerable<SelectListItem> Countries { get; set; }
}

RAZOR VIEW:

@model My_Web_App.Models.MyViewModel

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myform" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(model => model.ProjectName)
        <div class="col-md-9">
            @Html.EditorFor(model => model.ProjectName)
        </div>
    </div>

    <!-- Project Country -->
    <div class="form-group">
        @Html.LabelFor(model => model.ProjectCountry)
        <div class="col-md-4">
            @Html.DropDownListFor(
                x => x.ProjectCountry,
                new SelectList(Model.Countries, "Value", "Text"))
        </div>
    </div>

    <table id="mytable">
    <thead>
        <tr>
            <th>Data1</th>
            <th>Data2</th>
            <th>Data3</th>
        </tr>
    </thead>

    <tbody></tbody>
    </table>

    <button id="btnSubmit" type="submit">Submit</button>
}

<script type="text/javascript">
    $('#btnSubmit').click(function (event) {
        event.preventDefault();

        oTable = $('#mytable').dataTable({
            "ajax": {
                "url": "/MyController/MyJsonResult/",
                "type": "POST",
                "data": {
                    ProjectName: $('#ProjectName').val(),
                    ProjectCountry: $('#ProjectCountry').val()         
                }
            }
        });

    return false;
    });
</script>

CONTROLLER:

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult MyJsonResult()
{
    string projectName = Request["ProjectName"];
    string projectCountry = Request["ProjectCountry"];

    ... DO SOMETHING ...

    return Json(new { data = dosomethingresult }, JsonRequestBehavior.AllowGet);
}

The above code works in that I can get the View's form variables and use them to determine the results to return. Obviously I've left out a lot of code, a lot of form variables, and a lot of controller logic. I don't want to convert strings to integers, worry about whether a POST var is empty or null, etc. There are so many form variables I would like MVC to take care of this for me. For example:

上面的代码的工作原理是我可以获取View的表单变量并使用它们来确定要返回的结果。显然我遗漏了很多代码,很多表单变量和很多控制器逻辑。我不想将字符串转换为整数,担心POST var是空还是空等等。有很多表单变量我希望MVC为我处理这个问题。例如:

PREFERRED CONTROLLER ACTION:

首选控制器操作:

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult MyJsonResult(MyViewModel model)
{
    string projectName = model.ProjectName;
    string projectCountry = model.ProjectCountry;

    ... DO SOMETHING ...

    return Json(new { data = dosomethingresult }, JsonRequestBehavior.AllowGet);
}

The problem with the preferred controller action above is that the contents of model are always null when using DataTables Ajax.

上面首选控制器操作的问题是,在使用DataTables Ajax时,模型的内容始终为null。

model is initialized with valid data if I make the Ajax call outside of the DataTables initialization. :

如果我在DataTables初始化之外进行Ajax调用,则使用有效数据初始化model。 :

$('#btnSubmit').click(function (event) {
    event.preventDefault();

    $.ajax({
        url: "/MyController/MyJsonResult/",
        type: "POST",
        dataType: "json",
        data: $('#myform').serialize()
    });

    return false;
}

The data setting just above correctly serializes all of the form fields and MVC successfully creates the View Model object for me to use in the Controller Action. Unfortunately, "data": $('#myform').serialize() in the DataTables Ajax does not work. The model is uninitialized (nulls and zeros) when the Controller Action is called.

上面的数据设置正确地序列化了所有表单字段,MVC成功创建了View Model对象供我在Controller Action中使用。不幸的是,“数据”:DataTables Ajax中的$('#myform')。serialize()不起作用。调用Controller Action时,模型未初始化(nulls和0)。

How can I pass my entire form to the Controller Action using DataTables Ajax so that my View Model object contains correct data from the View's form?

如何使用DataTables Ajax将整个表单传递给Controller Action,以便我的View Model对象包含来自View表单的正确数据?

I have been searching for a solution for a long time. Way too long. :S

我一直在寻找解决方案。太久了。 :S

1 个解决方案

#1


0  

Try this in your Razor view:

在你的Razor视图中试试这个:

@using (Html.BeginForm("MyJsonResult", "MyController", FormMethod.Post, new { id = "myform" }))

#1


0  

Try this in your Razor view:

在你的Razor视图中试试这个:

@using (Html.BeginForm("MyJsonResult", "MyController", FormMethod.Post, new { id = "myform" }))