当前位置: 首页 > 面试题库 >

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

苏磊
2023-03-14
问题内容

我做了一个小项目,以了解Stephen Muecke的回答:在同一控制器上提交多次调用数据的PartialView吗?

几乎一切正常。javascript在Partial View中添加了新字段,我可以说它们是通过controller方法为部分视图插入的“
temp”值绑定到模型的。

但是,当我提交新字段时,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);
}

问题答案:

首先,通过创建一个视图模型来代表您要编辑的内容。我假设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)


 类似资料:
  • 使用采集: 普通文章采集 图片集采集

  • 采集帮助:  

  • 问题内容: 我有一个Person类,我想创建一棵树。这是Person类的解释器。 c1是左边的孩子,c2是右边的孩子。所以说我创建了三个这样的人: 因此,在这里您说亚当是根节点,亚当的左孩子是b,这是芭芭拉,他的右c是卡尔,依此类推。 所以我想做的是编写一个count方法,该方法计算包括在内的子代数。因此a.count()将返回6(如果Person f没有任何孩子)。 这是我的代码: 我在纸上运行

  • 本文向大家介绍winforms 使用帮助类显示帮助,包括了winforms 使用帮助类显示帮助的使用技巧和注意事项,需要的朋友参考一下

  • 问题内容: 我会将两个php变量从codeigniter控制器传递给位于我的视图顶部的javascript函数。有可能这样做吗? 问题答案: 是的,只要回显javascript: