使用 Html.BeginCollectionItem 帮助程序传递集合的局部视图

IT技术 javascript asp.net-mvc model-binding asp.net-mvc-partialview begincollectionitem
2021-02-08 08:33:53

我做了一个小项目来理解 Stephen Muecke 的答案:Submit same Partial View called multiple times data to controller?

几乎一切正常。javascript 从局部视图中添加了新字段,我可以通过控制器方法为局部视图插入的“临时”值判断它们已绑定到模型。

但是,当我提交新字段时,AddRecord() 方法抛出一个异常,表明模型没有被传入(“对象引用未设置为对象的实例”)。

此外,当我查看页面源代码时,BeginCollectionItem 助手会在主视图中的表格周围插入一个隐藏标记,因为它应该显示预先存在的记录,但不在 javascript 添加的新字段周围。

我究竟做错了什么?我在这方面很新,所以感谢您的耐心等待!

我的主要观点:

@model IEnumerable<DynamicForm.Models.CashRecipient>

@using (Html.BeginForm("AddDetail", "CashRecipients", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <div id="CSQGroup">
    </div>
}

<div>
    <input type="button" value="Add Field" id="addField" onclick="addFieldss()" />
</div>

<script>
    function addFieldss()
    {   
        //alert("ajax call");
        $.ajax({
            url: '@Url.Content("~/CashRecipients/RecipientForm")',
            type: 'GET',
            success:function(result) {
                //alert("Success");
                var newDiv = document.createElement("div"); 
                var newContent = document.createTextNode("Hi there and greetings!"); 
                newDiv.appendChild(newContent);  
                newDiv.innerHTML = result;
                var currentDiv = document.getElementById("div1");  
                document.getElementById("CSQGroup").appendChild(newDiv);
            },
            error: function(result) {
                alert("Failure");
            }
        });
    }
</script>

我的部分观点:

@model DynamicForm.Models.CashRecipient
@using HtmlHelpers.BeginCollectionItem

@using (Html.BeginCollectionItem("recipients"))
{
    <div class="editor-field">
        @Html.LabelFor(model => model.Id)
        @Html.LabelFor(model => model.cashAmount)
        @Html.TextBoxFor(model => model.cashAmount)
        @Html.LabelFor(model => model.recipientName)
        @Html.TextBoxFor(model => model.recipientName)
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
}

我的型号:

public class CashRecipient
{
    public int Id { get; set; }
    public string cashAmount { get; set; }
    public string recipientName { get; set; }  
}

在我的控制器中:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddDetail([Bind(Include = "Id,cashAmount,recpientName")] IEnumerable<CashRecipient> cashRecipient)
{
    if (ModelState.IsValid)
    {
        foreach (CashRecipient p in cashRecipient) {
            db.CashRecipients.Add(p);
        }
        db.SaveChanges();
        return RedirectToAction("Index");

    }

    return View(cashRecipient);
}

public ActionResult RecipientForm()
{
    var data = new CashRecipient();
    data.cashAmount = "temp";
    data.recipientName = "temp";
    return PartialView(data);
}
1个回答

首先创建一个视图模型来表示您要编辑的内容。我假设cashAmount是一个货币值,因此应该是一个小数(根据需要添加其他验证和显示属性)

public class CashRecipientVM
{
    public int? ID { get; set; }
    public decimal Amount { get; set; }
    [Required(ErrorMessage = "Please enter the name of the recipient")]
    public string Recipient { get; set; }  
}

然后创建一个局部视图(说) _Recipient.cshtml

@model CashRecipientVM
<div class="recipient">
    @using (Html.BeginCollectionItem("recipients"))
    {
        @Html.HiddenFor(m => m.ID, new { @class="id" })
        @Html.LabelFor(m => m.Recipient)
        @Html.TextBoxFor(m => m.Recipient)
        @Html.ValidationMesssageFor(m => m.Recipient)
        @Html.LabelFor(m => m.Amount)
        @Html.TextBoxFor(m => m.Amount)
        @Html.ValidationMesssageFor(m => m.Amount)
        <button type="button" class="delete">Delete</button>
    }
</div>

以及返回该部分的方法

public PartialViewResult Recipient()
{
    return PartialView("_Recipient", new CashRecipientVM());
}

那么你的主要 GET 方法将是

public ActionResult Create()
{
    List<CashRecipientVM> model = new List<CashRecipientVM>();
    .... // add any existing objects that your editing
    return View(model);
}

它的观点将是

@model IEnumerable<CashRecipientVM>
@using (Html.BeginForm())
{
    <div id="recipients">
        foreach(var recipient in Model)
        {
            @Html.Partial("_Recipient", recipient)
        }
    </div>
    <button id="add" type="button">Add</button>
    <input type="submit" value="Save" />
}

并将包含一个脚本来添加新的 html CashRecipientVM

var url = '@Url.Action("Recipient")';
var form = $('form');
var recipients = $('#recipients');
$('#add').click(function() {
    $.get(url, function(response) {
        recipients.append(response);
        // Reparse the validator for client side validation
        form.data('validator', null);
        $.validator.unobtrusive.parse(form);
    });
});

以及删除项目的脚本

$('.delete').click(function() {
    var container = $(this).closest('.recipient');
    var id = container.find('.id').val();
    if (id) {
        // make ajax post to delete item
        $.post(yourDeleteUrl, { id: id }, function(result) {
            container.remove();
        }.fail(function (result) {
            // Oops, something went wrong (display error message?)
        }
    } else {
        // It never existed, so just remove the container
        container.remove();
    }
});

表格将回发到

public ActionResult Create(IEnumerable<CashRecipientVM> recipients)
如果我尝试在不添加任何新项目的情况下提交它,它会在 foreach 上崩溃。这是如何防止的?
2021-03-18 08:33:53
我如何进行删除?
2021-03-22 08:33:53
谢谢斯蒂芬!这帮助我加载。
2021-03-22 08:33:53
@TravisTubbs,不确定你的意思,或者你得到了什么错误。由于这不是您的问题,我建议您提出一个问题,显示您使用的代码和错误的详细信息(但最好的猜测是您没有将模型传递给视图,因此foreach(var recipient in Model)会引发异常 - 您无法迭代null
2021-04-04 08:33:53
@TravisTubbs,请参阅从集合中删除项目的更新(以及重新解析验证器,以便您获得新项目的客户端验证
2021-04-07 08:33:53