如何在 ASP.Net MVC 5 中动态添加新行

2023-11-29

我正在寻求有关如何在 ASP.Net MVC 5 应用程序的创建 Razor 视图中向发票添加新行 LineItems 的帮助。我读过几乎所有类似的问题,但没有一个解决了我认为的简单用例。

这是我的发票模型类

public class Invoice
    {
        public int Id { get; set; }
        public int InvoiceNumber { get; set; }
        public List<LineItem> LineItems { get; set; }
        public Client Customer { get; set; }
        public DateTime DateCreated { get; set; }        
        public decimal Total { get; set; }            


        public Invoice()
        {
            LineItems = new List<LineItem>();
        }

请注意,此发票包含一个行项目列表,每个行项目都是一个简单的对象。并在 Invoice 构造函数中创建行项目列表。这是 LineItem 模型类

public class LineItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int Quantity { get; set; }
        public decimal Price { get; set; }        
        public decimal Total { get; set; }

    }

生成的 ASP.Net MVC 5 Razor 视图无法识别对象的 LineItems 列表,也不会为其创建任何条目。我想动态地将一行添加到下表中,并且我想让该行成为订单项的实例。

这是显示发票的表格

<table class="table table-condensed" id="invoiceTable"> 
      <thead>
         <tr id="invoiceTableHead">
             <td><strong>Item Name</strong></td>
             <td class="text-center"><strong>Item Description</strong></td>
             <td class="text-center"><strong>Item Price</strong></td>
             <td class="text-center"><strong>Item Quantity</strong></td>
             <td class="text-right"><strong>Total</strong></td>
          </tr>
       </thead>

     <tbody>

这是我尝试使用 JQuery 动态向该表追加一行,这就是我陷入困境的地方,任何帮助或指针将不胜感激。

  <script type="text/javascript">
    $("#lineItemButton").click(function () {
        debugger;
        // Create elements dynamically
        var newRow = "<tr><td>'@Html.TextBoxFor(x => x.LineItems, new { ??? What do int public here)'</td></tr>";

        // Add the new dynamic row after the last row
            $('#invoiceTable tr:last').after(newRow);
        });

    </script>

您可以创建动态行,但根据我的经验,它们不会绑定到模型。我有一个下拉列表,用户选择一个资产编号,然后单击“添加”按钮,动态地向表中添加新行。

我所做的是在表中创建一个隐藏行以使用模板。

   <table class="table table-bordered table-condensed table-hover" id="lineItemTable" name="assetTable">
                <thead>
                    <tr>
                        <th class="text-center">Item #</th>
                        <th class="text-center">Asset</th>
                        <th class="text-center">Condition</th>
                        <th class="text-center">Description 1</th>
                        <th class="text-center">Description 2</th>
                        <th class="text-center">Inventory Num</th>
                        <th class="text-center">Serial Number</th>
                    </tr>
                </thead>
                <tbody>
                    <tr hidden>
                        <td>
                            <label id="row"></label>

                        </td>
                        <td>
                            <input asp-for="TransferLineItem.AssisAsset" class="form-control" [email protected] />
                        </td>
                        <td>
                            <select asp-for="TransferLineItem.Condition" class="form-control" asp-items="@ViewBag.Conditions"></select>

                        </td>
                        <td>
                            <input asp-for="TransferLineItem.AssetDescription1" class="form-control" [email protected] />
                        </td>
                        <td>
                            <input asp-for="TransferLineItem.AssetDescription2" class="form-control" [email protected] />
                        </td>
                        <td>
                            <input asp-for="TransferLineItem.InventoryNum" class="form-control"  />
                        </td>
                        <td>
                            <input asp-for="TransferLineItem.SerialNumber" class="form-control" [email protected] />
                        </td>
                    </tr>
                </tbody>
            </table>

单击添加按钮时,我使用 jQuery 克隆隐藏的表行并在表中追加新行。我在每个控件的 id 后附加“_[行号]”,以便每个控件都有唯一的 id 号。

    //clones the first row of the table
var newRow = $("#lineItemTable tbody tr").first().clone();

//removes the 'hidden' attribute so it will be visible when added  to the table
newRow.removeAttr("hidden");

//add/append new row to the table
$("tbody").append(newRow);

//get row number which will be appended to the id of each control in this row
//for example if this were  the second row then the id of the asset field would be something like asset_2.  
//note  that since there is already a hidden row in the table, we subtract 1 from the row number
var rowNum = "_" + ($("#lineItemTable tbody tr").length-1);

//loop through the input controls and add the new id value
newRow.find("input").each(function () {

    // get id of the input control
    var ctrl = $(this).attr("id");

    //concatenate the row number to the id
    var newId = ctrl + rowNum;

    //assign new id to control
    $(this).attr("id", newId);

});

为了将数据保存在 html 表中,我使用 jQuery 为每行创建一个名称/值对数组,并将其传递给控制器​​中的函数。

 //get table
var tbl = document.getElementById("lineItemTable");

//array to hold the json objects
var jsonArray = [];

//iterate through the fields and put values in the json object
for (var i = 1, r = tbl.rows.length-1; i < r; i++)
{

    var jsonObj = {
        asset: $("#TransferLineItem_AssisAsset_" + i).val(),
        condition: $("#TransferLineItem_Condition_" + i).val(),
        assetDescription1: $("#TransferLineItem_AssetDescription1_" + i).val(),
        assetDescription2: $("#TransferLineItem_AssetDescription2_" + i).val(),
        InventoryNum: $("#TransferLineItem_InventoryNum_" + i).val(),
        serialNumber: $("#TransferLineItem_SerialNumber_" + i).val()
    };

    //put json object in array
    jsonArray.push(jsonObj);

}


//pass json array to controller function to save line items
$.ajax({
    type: "GET",
    url: "Create?handler=SaveTransferLineItems",
    contentType: "application/json; charset=utf-8'",
    data: { jsonObj: JSON.stringify(jsonArray) },
    success: function () {
        showModal("btn-success", "Form Saved", "Your new transfer form was successfully saved.");
        },
    failure: function () {
        showModal("btn-danger", "Save Failed", "Your form could not be saved, please contact site support");
      }
});

在控制器函数中,我将名称值对转换为“TransferLineItem”类型的列表(绑定模型)。我可以迭代列表并使用上下文将其保存到数据库。

 dynamic _json = JsonConvert.DeserializeObject<List<TransferLineItem>>(jsonObj);

        foreach (TransferLineItem  item in _json)
        {

            try
            {
                _context.TransferLineItem.Add(item);


                int x = await _context.SaveChangesAsync();

                if (x != 1)
                {
                    ModalMessage = "Could not save items, starting at " + TransferLineItem.Asset;
                    return Page();
                }

            }
            catch (Exception ex)
            {
                ModalType = "btn-danger";
                ModalTitle = "Save Failed";
                ModalMessage = ex.Message;
                return Page();
            }


        }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 ASP.Net MVC 5 中动态添加新行 的相关文章

随机推荐

  • 在链表的开头插入新节点

    在 C 语言的简单链表实现中 我无法找出一行名为 insert 的函数 它需要一个字符并按字母顺序添加到链接列表中 该行是关于当列表为空时创建一个新节点 由于列表上只有一个节点 因此该行应该像我评论的那样 我错了吗 void insert
  • 复杂MySQL查询错误结果

    我正在尝试构建复杂的 mysql 查询 但它返回错误的结果 SELECT b name AS batch name b id AS batch id COUNT DISTINCT s id AS total students COALESC
  • 如何在我的应用程序中将状态栏设置为白色背景和黑色文本(黑色图标)

    我想在我的应用程序中将状态栏设置为白色背景和黑色文本 和黑色图标 我发现一些应用程序可以做到这一点 但是从谷歌搜索 我找不到任何解决方案来做到这一点 有很多关于如何设置状态栏颜色的解决方案 还有像 SystemBarTint 它只能设置背景
  • 使用 jQuery 获取当前 URL? [复制]

    这个问题在这里已经有答案了 我正在使用 jQuery 如何获取当前 URL 的路径并将其分配给变量 示例网址 http localhost menuname de foo bar amp number 0 要获取路径 您可以使用 var p
  • 如何通过脚本创建 crontab

    我需要通过运行来设置服务器的脚本添加一个 cron 作业 我目前正在使用Ubuntu 我可以用crontab e但这将打开一个编辑器来编辑当前的 crontab 我想以编程方式执行此操作 可以这样做吗 这是一个不使用 不要求新作业位于文件中
  • 如何在循环遍历向量时从向量中删除元素?

    我正在循环遍历一个带有循环的向量 例如for int i 0 i lt vec size i 在此循环中 我检查该向量索引处元素的条件 如果某个条件为真 我想删除该元素 如何在循环遍历向量元素时删除向量元素而不崩溃 从 STL 容器中删除满
  • Python - 在列表理解中保留计数器

    是否可以为以下循环编写列表理解 m counter 0 for i x in enumerate l if x field something counter 1 m append counter i 我不知道如何增加列表理解中的计数器 你
  • Symfony - 未找到表单请求的 url

    我正在从事 symfony 项目 我正在与一个不会重定向到自己页面的表单作斗争 action 属性设置为 method 设置为 post 在这种情况下 它应该调用同一页面 但我会以 404 页面结束 这是我的页面在操作文件中的代码 公共函数
  • 无法识别的选择器发送到实例

    我向核心数据支持的 UITableView 添加了索引搜索 搜索工作正常 但是导航回 tableView 后出现此错误 NSSQLRow controllerDidChangeContent 无法识别的选择器发送到实例 0x815edf0
  • javascript - 在单击再次起作用之前需要 onclick 走完全程

    我有这个 javascript 函数 我使用它 当单击时会移动一定的距离 这是在使用大约 7 个 div 的从左到右的滚动条中使用的 我的问题是 在再次使用点击之前 如何让点击先走完整距离 问题是 如果用户快速单击箭头按钮 它会重置距离 有
  • 在属性窗口中更改自定义属性时不会保存

    我为 DataGridView 创建了一个自定义列 原因是我想向列添加属性 类型 我右键单击 DataGridView 并选择 编辑列 然后 当我选择作为自定义列类型的列时 我可以编辑该属性 但如果我在编辑后单击 确定 然后再次转到 编辑列
  • iOS 8 中 UIKeyboardWillShowNotification 的行为是否有变化?

    我有一个简单的UIView块动画 用于在键盘显示时将一组文本字段动画化到视图中 并在键盘隐藏时将它们动画化回来 这在 iOS 6 和 7 中工作得很好 但现在我得到了不正确的行为 这一切都表明了一些变化UIKeyboardWillShowN
  • 查询包含对不同数据上下文中定义的项目的引用

    我在 Stackoverflow 上阅读了其他几篇文章 但我的问题很简单且不同 我有 2 个独立的数据库 这就是为什么我有两个独立的 Datacontext 这是我的查询 我在其中传递参数并将其绑定到我的 GridView if Sessi
  • Ruby/Rails - 如何根据十进制进行验证?

    如何根据小数位数进行验证 例如 假设我们要存储小数点后最多 2 位小数的酒店评级 4 34 3 76 ETC 我在网上读到了基于您与列绑定的精度 比例截断的 sqlite 因此 如果您的精度为 3 小数位数为 2 并输入 1 34567 则
  • 将特定文件复制到新文件夹,同时保留原始子目录树

    我有一个大目录 其中有许多子目录 我正在尝试对其进行排序 我正在尝试将特定文件类型复制到新文件夹 但我想保留原始子目录 def copyFile src dest try shutil copy src dest except shutil
  • 交换两个变量的 XOR 技巧如何真正在字符串上起作用?

    我刚刚遇到了这段代码 用于在 PHP 中交换两个变量的值
  • 检查 iOS 模拟器类型和版本

    我有以下代码片段来检测 iOS 设备 NSString platformNSString size t size sysctlbyname hw machine NULL size NULL 0 char machine malloc si
  • 我可以在 MySQL 下直接在 SQL 中运行 HTTP GET 吗?

    我很乐意这样做 UPDATE table SET blobCol HTTPGET urlCol WHERE whatever LIMIT n 有代码可以做到这一点吗 我知道这应该是可能的 因为MySQL 文档包括添加执行 DNS 查找的函数
  • 等待与事件处理程序异步

    我对如何最好地处理这种情况感到困惑 我不想等待异步调用的响应 具体来说我有 public async Task
  • 如何在 ASP.Net MVC 5 中动态添加新行

    我正在寻求有关如何在 ASP Net MVC 5 应用程序的创建 Razor 视图中向发票添加新行 LineItems 的帮助 我读过几乎所有类似的问题 但没有一个解决了我认为的简单用例 这是我的发票模型类 public class Inv