Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 使用ajax将html动态表中的数据发布到控制器_Jquery_Asp.net Mvc - Fatal编程技术网

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

Jquery 使用ajax将html动态表中的数据发布到控制器,jquery,asp.net-mvc,Jquery,Asp.net Mvc,这是我的桌子 <table class="customtable" width="100%"> <thead> <tr> <td> <div style="width: 80px">Employee ID</div> </td> <td> &l

这是我的桌子

<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>

员工ID
员工姓名:
员工类型
@foreach(var工作日在日列表中){
@工作日价值

@workDay.Key} @对于(int i=0;i @Model.LineItems[i].EmployeeNo) @DisplayFor(m=>@Model.LineItems[i].EmployeeName) @Html.DisplayFor(m=>@Model.LineItems[i].EmployeeType)@for(int j=0;j m.LineItems[i].EmployeeLineItems[j].ShiftCode,MVC.Shared.Views.editoremplates.shiftdepicker)}
我想通过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)";
        }
    });
}
函数ajaxAdd(){
var i=0;
var模型;
对于(i=0;i<10;i++){
型号={
'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)”,
类型:“post”,
数据:JSON.stringify(模型),
contentType:'应用程序/json',
成功:函数(){
window.location.href=“@Url.Action(MVC.WorkSchedule.ActionNames.Create,MVC.WorkSchedule.Name)”;
}
});
}
当我传递诸如
$(“#@Html.FieldIdFor(m=>m.LineItems[0].EmployeeLineItems[1].ShiftCode]”)之类的值时,.val()
我可以在控制器方法中获得该值。但一旦我用“我”来代替它们,它就不起作用了


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

我没有您模型的详细信息,但考虑到您提供的标记和代码,我使用
Microsoft jQuery Unobtrusive ajax来提取此示例(如果尚未安装,则必须安装它,使用Nuget是最简单的方法。在Nuget控制台中,输入
install Package Microsoft.jQuery.Unobtrusive.Ajax
。也可以使用Nuget Packages管理器)

这就像预期的那样工作(通过AJAX发送到action
EmployeesPost
)shift code文本框中的新值

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

 bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
                "~/Scripts/jquery.unobtrusive-ajax.js"));
以下是我为复制您的模型而创建的模型: (我把所有这些都放在
EmployeeViewModels.cs
文件夹下的
Models文件中)

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

视图(
/Views/Employee/Index.cshtml

最后,我创建了
EditorTemplate
Views/Shared/EditorTemplates/ShiftCodePicker.chtml


感谢您的回复。对于此要求,我需要两个按钮。一个是向表中添加行。另一个是保存表。我的问题是第一个。对于保存按钮,我在[Httppost]中获取值方法。但对于另一个添加按钮,它正在向表中添加行。我需要的是获取已选择移位码选择器的现有模型。然后添加一个具有默认移位码的新行。并将其传递回视图。这就是我需要获取模型的位置。(我尝试添加图像,但需要10个积分:(您可以将一个属性添加到您的模型(例如,
public bool HasToAddRow{get;set;}
)中,将其作为隐藏在视图上,并在事件中单击按钮更改该隐藏属性的值。然后在操作(
EmployeePost
)中,您可以使用
if
处理所需内容:(`if(model.HasToAddRow){//add row}else{//save})@ISP我根据您的评论修改了我的帖子。您可以看到我向模型中添加了一个属性,并且我修改了视图和控制器来管理这个新属性。现在您可以通过单击
添加行
按钮来添加行。@ISP我还编辑了部分视图,以使演示正常工作。谢谢..添加该字段就可以了谢谢你的帮助。
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"}
            };
        }
    }
}
    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);
                }
            }
        }
    }
@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>
}
@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>
@model ExemplesApplication.Models.ShiftCode

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