栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

首先,通过创建一个视图模型来代表您要编辑的内容。我假设

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 >    @using (Html.BeginCollectionItem("recipients"))    {        @Html.HiddenFor(m => m.ID, new { @ })        @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" >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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415917.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号