Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.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
C# 发布表单数组而不成功_C#_Html_Asp.net Mvc_Forms - Fatal编程技术网

C# 发布表单数组而不成功

C# 发布表单数组而不成功,c#,html,asp.net-mvc,forms,C#,Html,Asp.net Mvc,Forms,我正在用C#和.NETFramework4.5.1开发一个ASP.NETMVC5Web 我在cshtml文件中有这个表单: @model MyProduct.Web.API.Models.ConnectBatchProductViewModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-w

我正在用C#和.NETFramework4.5.1开发一个ASP.NETMVC5Web

我在
cshtml
文件中有这个
表单

@model MyProduct.Web.API.Models.ConnectBatchProductViewModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    @if (@Model != null)
    { 
        <h4>Producto: @Model.Product.ProductCode, Cantidad: @Model.ExternalCodesForThisProduct</h4>
        using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post))
        {
            @Html.HiddenFor(model => model.Product.Id, new { @id = "productId", @Name = "productId" });

            <div>
                <table id ="batchTable" class="order-list">
                    <thead>
                        <tr>
                            <td>Cantidad</td>
                            <td>Lote</td>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>@Html.TextBox("ConnectBatchProductViewModel.BatchProducts[0].Quantity")</td>
                            <td>@Html.TextBox("ConnectBatchProductViewModel.BatchProducts[0].BatchName")</td>
                            <td><a class="deleteRow"></a></td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="5" style="text-align: left;">
                                <input type="button" id="addrow" value="Add Row" />
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <p><input type="submit" value="Seleccionar" /></p>
        }
    }
    else
    { 
        <div>Error.</div>
    }
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script src="~/js/createBatches.js"></script> <!-- Resource jQuery -->    
</body>
</html>
和两个
ViewModel

public class BatchProductViewModel
{
    public int Quantity { get; set; }
    public string BatchName { get; set; }
}

public class ConnectBatchProductViewModel
{
    public Models.Products Product { get; set; }
    public int ExternalCodesForThisProduct { get; set; }

    public IEnumerable<BatchProductViewModel> BatchProducts { get; set; }
}
public ActionResult Save(int productId, IEnumerable<BatchProductViewModel> model);
如果使用上述方法签名,则两个参数都为null


我需要一个
IEnumerable
,因为用户将使用jQuery动态添加更多行

这是
jQuery
脚本:

jQuery(document).ready(function ($) {
    var counter = 0;

    $("#addrow").on("click", function () {

        counter = $('#batchTable tr').length - 2;

        var newRow = $("<tr>");
        var cols = "";

        var quantity = 'ConnectBatchProductViewModel.BatchProducts[0].Quantity'.replace(/\[.{1}\]/, '[' + counter + ']');
        var batchName = 'ConnectBatchProductViewModel.BatchProducts[0].BatchName'.replace(/\[.{1}\]/, '[' + counter + ']');

        cols += '<td><input type="text" name="' + quantity + '"/></td>';
        cols += '<td><input type="text" name="' + batchName + '"/></td>';

        cols += '<td><input type="button" class="ibtnDel"  value="Delete"></td>';
        newRow.append(cols);

        $("table.order-list").append(newRow);
        counter++;
    });


    $("table.order-list").on("click", ".ibtnDel", function (event) {
        $(this).closest("tr").remove();

        counter -= 1
        $('#addrow').attr('disabled', false).prop('value', "Add Row");
    });
});
jQuery(文档).ready(函数($){
var计数器=0;
$(“#添加行”)。在(“单击”上,函数(){
计数器=$('#batchTable tr')。长度-2;
var newRow=$(“”);
var cols=“”;
变量数量='ConnectBatchProductViewModel.BatchProducts[0].quantity'。替换(/\[.{1}\]/,'['+计数器+']);
var batchName='ConnectBatchProductViewModel.BatchProducts[0].batchName'。替换(/\[.{1}\]/,'['+计数器+']);
cols+='';
cols+='';
cols+='';
newRow.append(cols);
$(“table.order list”).append(newRow);
计数器++;
});
$(“table.order list”)。在(“click”、“.ibtnDel”上,函数(事件){
$(this).tr.remove();
计数器-=1
$('#addrow').attr('disabled',false).prop('value','addrow');
});
});
有什么想法吗


我已经检查过了,但是我的代码无法正常工作。

在您的Post方法中,您会收到“MyProduct.Web.API.Models.ConnectBatchProductViewModel”作为参数。
将现有模型用于Post方法


为什么要从模型中获取IEnumerable?只有一个可用控件包含模型中的id。

您需要在
for
循环中为集合生成控件,以便使用索引器正确命名这些控件(请注意,属性
BatchProducts
需要为
IList

编辑

注意:编辑之后,如果要在视图中动态添加和删除
BatchProductViewModel
项,则需要使用
BeginCollectionItem
帮助程序或html模板,如中所述

动态添加新项目的模板将是

<div id="NewBatchProduct" style="display:none">
  <tr>
    <td><input type="text" name="BatchProducts[#].Quantity" value /></td>
    <td><input type="text" name="BatchProducts[#].BatchName" value /></td>
    <td>
      <input type="hidden" name="BatchProducts.Index" value ="%"/>
      <a class="deleteRow"></a>
    </td>
  </tr>
</div>
您可以访问以获取完整的源代码

您必须首先创建一个操作,从中我们可以传递对象列表

[HttpGet]
public ActionResult Index()
{
    List<Contact> model = new List<Contact>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        model = dc.Contacts.ToList();
    }
    return View(model);
}
[HttpGet]
公共行动结果索引()
{
列表模型=新列表();
使用(MyDatabaseEntities dc=new MyDatabaseEntities())
{
model=dc.Contacts.ToList();
}
返回视图(模型);
}
然后我们需要为该操作创建一个视图

@model List<UpdateMultiRecord.Contact>
@{
    ViewBag.Title = "Update multiple row at once Using MVC 4 and EF ";
}
@using (@Html.BeginForm("Index","Home", FormMethod.Post))
{
    <table>
            <tr>
                <th></th>               
                <th>Contact Person</th>
                <th>Contact No</th>
                <th>Email ID</th>
            </tr>
        @for (int i = 0; i < Model.Count; i++)
        {
            <tr>               
                <td> @Html.HiddenFor(model => model[i].ContactID)</td>
                <td>@Html.EditorFor(model => model[i].ContactPerson)</td>
                <td>@Html.EditorFor(model => model[i].Contactno)</td>
                <td>@Html.EditorFor(model => model[i].EmailID)</td>
            </tr>
        }
    </table>
    <p><input type="submit" value="Save" /></p>
    <p style="color:green; font-size:12px;">
        @ViewBag.Message
    </p>
}
 @section Scripts{
    @Scripts.Render("~/bundles/jqueryval")
 }
@型号列表
@{
ViewBag.Title=“使用MVC4和EF一次更新多行”;
}
@使用(@Html.BeginForm(“Index”,“Home”,FormMethod.Post))
{
联系人
联系电话
电子邮件ID
@for(int i=0;imodel[i].ContactID)
@EditorFor(model=>model[i].ContactPerson)
@EditorFor(model=>model[i].Contactno)
@Html.EditorFor(model=>model[i].EmailID)
}

@查看包。留言

} @节脚本{ @Scripts.Render(“~/bundles/jqueryval”) }
然后我们必须编写代码,将对象列表保存到数据库中

[HttpPost]
public ActionResult Index(List<Contact> list)
{  
    if (ModelState.IsValid)
    {
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            foreach (var i in list)
            {
                var c = dc.Contacts.Where(a =>a.ContactID.Equals(i.ContactID)).FirstOrDefault();
                if (c != null)
                {
                    c.ContactPerson = i.ContactPerson;
                    c.Contactno = i.Contactno;
                    c.EmailID = i.EmailID;
                }
            }
            dc.SaveChanges();
        }
        ViewBag.Message = "Successfully Updated.";
        return View(list);
    }
    else
    {
        ViewBag.Message = "Failed ! Please try again.";
        return View(list);
    }
}
[HttpPost]
公共行动结果索引(列表)
{  
if(ModelState.IsValid)
{
使用(MyDatabaseEntities dc=new MyDatabaseEntities())
{
foreach(列表中的变量i)
{
var c=dc.Contacts.Where(a=>a.ContactID.Equals(i.ContactID)).FirstOrDefault();
如果(c!=null)
{
c、 联系人=即联系人;
c、 Contactno=i.Contactno;
c、 EmailID=i.EmailID;
}
}
dc.SaveChanges();
}
ViewBag.Message=“已成功更新。”;
返回视图(列表);
}
其他的
{
ViewBag.Message=“失败!请重试。”;
返回视图(列表);
}
}
使用(Html.BeginForm())
{
//代码在这里

}
遵循DRY原则,您可以为此创建一个EditorTemplate。 步骤:

1-在视图>共享>创建名为(EditorTemplates)的新文件夹中

2-在新创建的EditorTemplates文件夹中创建视图,根据OP示例,视图的模型应为BatchProductViewModel。将代码放在编辑器视图中。不需要循环或索引

EditorTemplate的行为与每个子实体的PartialView相似,但更为通用

3-在父实体的视图中,调用编辑器: @EditorFor(m=>m.BatchProducts)


这不仅提供了一个更有条理的视图,还让您可以在其他视图中重复使用相同的编辑器。

请同时发布
BatchProductViewModel
的代码……另外,在您的操作方法中,您确定您的意图是使用
BatchProductViewModel
而不是
ConnectBatchProductViewModel
?@Ruslan Question已更新。视图中的模型是
ConnectBatchProductViewModel
如果要为
BatchProductViewModel
的集合生成视图,则视图必须是
IEnumerable
且POST方法参数必须相同(不要使用
FormCollection
)而
BatchProductViewModel
的控件需要在
for
循环中生成,并且
int-productId
将永远不会绑定,因为控件的名称是
Product.Id
(不是productId)。如果将方法更改为
公共操作结果保存(ConnectBatchProductViewModel模型)
您将看到它是正确的。我已经更新了我的问题。我已经更改了
$("#addrow").click(function() {
  var index = (new Date()).getTime(); // unique indexer
  var clone = $('#NewBatchProduct').clone(); // clone the BatchProducts item
  // Update the index of the clone
  clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
  clone.html($(clone).html().replace(/"%"/g, '"' + index  + '"'));
  $("table.order-list").append(clone.html());
});
[HttpGet]
public ActionResult Index()
{
    List<Contact> model = new List<Contact>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        model = dc.Contacts.ToList();
    }
    return View(model);
}
@model List<UpdateMultiRecord.Contact>
@{
    ViewBag.Title = "Update multiple row at once Using MVC 4 and EF ";
}
@using (@Html.BeginForm("Index","Home", FormMethod.Post))
{
    <table>
            <tr>
                <th></th>               
                <th>Contact Person</th>
                <th>Contact No</th>
                <th>Email ID</th>
            </tr>
        @for (int i = 0; i < Model.Count; i++)
        {
            <tr>               
                <td> @Html.HiddenFor(model => model[i].ContactID)</td>
                <td>@Html.EditorFor(model => model[i].ContactPerson)</td>
                <td>@Html.EditorFor(model => model[i].Contactno)</td>
                <td>@Html.EditorFor(model => model[i].EmailID)</td>
            </tr>
        }
    </table>
    <p><input type="submit" value="Save" /></p>
    <p style="color:green; font-size:12px;">
        @ViewBag.Message
    </p>
}
 @section Scripts{
    @Scripts.Render("~/bundles/jqueryval")
 }
[HttpPost]
public ActionResult Index(List<Contact> list)
{  
    if (ModelState.IsValid)
    {
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            foreach (var i in list)
            {
                var c = dc.Contacts.Where(a =>a.ContactID.Equals(i.ContactID)).FirstOrDefault();
                if (c != null)
                {
                    c.ContactPerson = i.ContactPerson;
                    c.Contactno = i.Contactno;
                    c.EmailID = i.EmailID;
                }
            }
            dc.SaveChanges();
        }
        ViewBag.Message = "Successfully Updated.";
        return View(list);
    }
    else
    {
        ViewBag.Message = "Failed ! Please try again.";
        return View(list);
    }
}