使用ajax将html动态表中的数据发布到控制器

时间:2014-12-02 03:58:24

标签: jquery asp.net-mvc

这是我的表格。

<table class="customtable" width="100%">
    <thead>
        <tr>
            <td>
                <div style="width: 80px">Employee ID</div>
            </td>
            <td>
                <label class="control-label">Employee Name:</label>
            </td>
            <td>
                <div style="width: 100px">Employee Type</div>
            </td>@foreach (var workDay in dayList) {
            <td>@workDay.Value
                <br>&nbsp; @workDay.Key</td>}</tr>
    </thead>
    <tbody>@for (int i = 0; i
        < Model.LineItems.Count; i++) { <tr>
            <td>@Html.DisplayFor(m =>@Model.LineItems[i].EmployeeNo)</td>
            <td>@Html.DisplayFor(m => @Model.LineItems[i].EmployeeName)</td>
            <td>@Html.DisplayFor(m => @Model.LineItems[i].EmployeeType)</td>@for (int j = 0; j
            < Model.LineItems[i].EmployeeLineItems.Count; j++) { <td>@Html.EditorFor(m => m.LineItems[i].EmployeeLineItems[j].ShiftCode, MVC.Shared.Views.EditorTemplates.ShiftCodePicker)</td>}</tr>}</tbody>
</table>

我想通过ajax post方法将其传递给控制器​​

function ajaxAdd() {
    var i = 0;
    var model;
    for (i = 0; i < 10; i++) {
        model = {
            'EmployeeId': $("#@Html.FieldIdFor(m => m.EmployeeId)").val(),
                'SignatureId': $("#@Html.FieldIdFor(m => m.SignatureId)").val(),
                'StoreId': $("#@Html.FieldIdFor(m => m.StoreId)").val(),
                'ScheduleDate': $("#@Html.FieldIdFor(m => m.ScheduleDate)").val(),
                'LineItems[0].EmployeeLineItems[1].ShiftCode': $("#@Html.FieldIdFor(m => m.LineItems[0].EmployeeLineItems[1].ShiftCode)").val()
        };
    }


    $.ajax({
        url: "@Url.Action(MVC.WorkSchedule.ActionNames.AddNew, MVC.WorkSchedule.Name)",
        type: "post",
        data: JSON.stringify(model),
        contentType: 'application/json',
        success: function () {

            window.location.href = "@Url.Action(MVC.WorkSchedule.ActionNames.Create, MVC.WorkSchedule.Name)";
        }
    });
}

当我传递像$("#@Html.FieldIdFor(m => m.LineItems[0].EmployeeLineItems[1].ShiftCode)").val()这样的值时,我可以在控制器方法中获得该值。但是一旦我用“我”替换它们就行不通。

有没有其他方法可以使用ajax post方法将此数据发送到控制器?

1 个答案:

答案 0 :(得分:1)

我没有您的模型的详细信息,但鉴于您提供的标记和代码,我使用Microsoft jQuery Unobtrusive Ajax提取此示例(如果您还没有安装它,使用Nuget是最简单的方法。在Nuget控制台中输入Install-Package Microsoft.jQuery.Unobtrusive.Ajax。您也可以使用NuGet包管理器。

这可以按预期的方式发送到服务器(通过AJAX进入动作EmployeesPost)移位代码TextBox上的新值。

安装Microsoft.jQuery.Unobtrusive.Ajax后,您必须在BundleConfig.cs文件夹下的App_Start文件夹中添加一个包,如下所示:

 bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
                "~/Scripts/jquery.unobtrusive-ajax.js"));

以下是我试图重现你的模型: (我把所有这些都放在EmployeeViewModels.cs文件夹下的Models文件中)

using System.Collections.Generic;

    namespace ExemplesApplication.Models
    {
        public class ShiftCode
        {
            public string Name { get; set; }
        }
        public class EmployeeLine
        {
            public ShiftCode ShiftCode { get; set; }
        }
        public class Employee
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Type { get; set; }
        public List<EmployeeLine> EmployeeLineItems { get; set; }

        public Employee()
        {
            EmployeeLineItems = new List<EmployeeLine>
            {
                new EmployeeLine {ShiftCode = new ShiftCode {Name = "Morning" }},
                new EmployeeLine {ShiftCode = new ShiftCode {Name = "NOON"}},
                new EmployeeLine {ShiftCode = new ShiftCode {Name = "Afternoon"}},
                new EmployeeLine {ShiftCode = new ShiftCode {Name = "evening"}},
                new EmployeeLine {ShiftCode = new ShiftCode {Name = "Night"}}
            };
        }
    }
    public class EmployeesViewModel
    {
        public bool HaveToAddRow { get; set; }
        public Dictionary<string, string> WorkDays
        {
            get
            {
                return new Dictionary<string, string>
                {
                    {"Monday", "1"},
                    {"Tuesday", "2"},
                    {"Wednesday", "3"},
                    {"Thursday", "4"},
                    {"Friday", "5"}
                };
            }
        }

        public List<Employee> Employees { get; set; }

        public EmployeesViewModel()
        {
            Employees = new List<Employee>
            {
                new Employee {Id = 1, Name = "Robert", Type = "Engineer"},
                new Employee {Id = 2, Name = "Albert", Type = "Driver"},
                new Employee {Id = 3, Name = "Fred", Type = "Manager"},
                new Employee {Id = 4, Name = "Thomas", Type = "Sales"},
                new Employee {Id = 5, Name = "Sahra", Type = "Engineer"}
            };
        }
    }
}

然后控制器看起来像这样(EmployeeController.cs):

    using ExemplesApplication.Models;
    using System.Web.Mvc;

    namespace ExemplesApplication.Controllers
    {
        public partial class EmployeeController : Controller
        {
            public virtual ActionResult Index()
            {
                return View(new EmployeesViewModel());
            }

            public virtual ActionResult EmployeesPost(EmployeesViewModel model)
            {
                if (model.HaveToAddRow)
                {
                    //add row
                    model.Employees.Add(new Employee {Id = 1, Name = "New employee", Type = "Engineer"});
                    return PartialView(MVC.Employee.Views._TableEmployees, model);
                }
                else
                {
                    // your logic to save 
                    //here

                    // render the partial view
                    return PartialView(MVC.Employee.Views._TableEmployees, model);
                }
            }
        }
    }

然后我创建了一个视图和一个局部视图:

查看(/Views/Employee/Index.cshtml

@model ExemplesApplication.Models.EmployeesViewModel
@{
    ViewBag.Title = "Employees";

    var ajaxOptions = new AjaxOptions {UpdateTargetId = "employees-table-container", Url = Url.Action(MVC.Employee.EmployeesPost())};
}

<h2>Index</h2>

@using(Ajax.BeginForm(ajaxOptions))
{
    @Html.HiddenFor(m=>m.HaveToAddRow)
    <div id="employee-container">
        <div id="employees-table-container">
            @Html.Partial(MVC.Employee.Views._TableEmployees, Model)
        </div>
        <input id="add-row" type="button" value="Add Row" />
        <input id="save-table"type="submit" value="Submit" />
    </div>
}

@section scripts
{
    @Scripts.Render("~/bundles/jqueryajax")
    <script type="text/javascript">
        $(document).ready(function () {
            var $form = $("form"),
                $haveToAddRowHidden = $("#HaveToAddRow");

            $("#add-row").on("click", function() {
                $haveToAddRowHidden.val(true);
                $form.submit();
            });

            $("#save-table").on("click", function () {
                $haveToAddRowHidden.val(false);
            });
        });
    </script>
}

PartialView(/Views/Employee/_TableEmployees.cshtml

@model ExemplesApplication.Models.EmployeesViewModel

<table class="customtable" width="100%">
    <thead>
        <tr>
            <td>
                <div style="width: 80px">Employee ID</div>
            </td>
            <td>
                <label class="control-label">Employee Name:</label>
            </td>
            <td>
                <div style="width: 100px">Employee Type</div>
            </td>
            @foreach (var workDay in Model.WorkDays)
            {
                <td>
                    @workDay.Value
                    <br>&nbsp; @workDay.Key
                </td>
            }
        </tr>
    </thead>
    <tbody>
        @for (var i = 0; i < Model.Employees.Count(); i++)
        {
            <tr>
                <td>
                    @Html.DisplayFor(m => @Model.Employees[i].Id)
                    @Html.HiddenFor(m => @Model.Employees[i].Id)
                </td>
                <td>
                    @Html.DisplayFor(m => @Model.Employees[i].Name)
                    @Html.HiddenFor(m => @Model.Employees[i].Name)
                </td>
                <td>
                    @Html.DisplayFor(m => @Model.Employees[i].Type)
                    @Html.HiddenFor(m => @Model.Employees[i].Type)
                </td>
                @for (var j = 0; j < Model.Employees[i].EmployeeLineItems.Count; j++)
                {
                    <td>@Html.EditorFor(m => m.Employees[i].EmployeeLineItems[j].ShiftCode, MVC.Shared.Views.EditorTemplates.ShiftCodePicker)</td>
                }
            </tr>
        }
    </tbody>
</table>

最后我创建了EditorTemplateViews/Shared/EditorTemplates/ShiftCodePicker.chtml

@model ExemplesApplication.Models.ShiftCode

@Html.TextBoxFor(m=> m.Name, new { @class = "editor-for-shiftcode" })