我是ASP.NET MVC的新手,如果这比看起来更容易,那么道歉.我一直在谷歌上搜索,我有一个这样的课:
public class Search : IAuditable { [Key] public int SearchID { get; set; } public int UserID { get; set; } ... public ICollection<SearchTerm> SearchTerms { get; set; } }
在Create.cshtml中,我有以下内容
<div class="editor-label"> @Html.LabelFor(model => model.Search.SearchTerms) </div> <div class="editor-field"> @Html.EditorFor(model => model.Search.SearchTerms,"SearchTerm") @Html.ValidationMessageFor(model => model.Search.SearchTerms) </div>
SearchTerm EditorTemplate是一个简单的表单,如下所示:
@model Core.Search.Parameters.SearchTerm @Html.HiddenFor(n => n.SearchTermID) <div class="editor-label"> @Html.LabelFor(n => n.Text,"Term") </div> <div class="editor-field"> @Html.EditorFor(n => n.Text) @Html.ValidationMessageFor(n => n.Text) </div>
它似乎工作,我在创建时看到一个文本框(当默认模型为空时).但是,我想要做的是能够使用“添加”按钮添加/删除SearchTerms,以便用户可以在创建时向集合中添加任意数量的术语.这是以某种方式建造的吗?是否有一个与此配对良好的javascript框架,它将生成相应的html名称,所以我不必手动执行此操作?鉴于我是MVC的新手,我是否正确地接近这一点?
谢谢!
解决方法
在这种情况下,我更喜欢使用PartialView.
您应该创建一个ActionResult,它会为您的项目返回PartialView.当您单击“添加”按钮时,您应该向此ActionResult发送ajax请求.
public ActionResult GetTermItem() { return PartialView("_SearchTerm",new SearchTerm()); }
您的PartialView应如下所示:
@model Core.Search.Parameters.SearchTerm @{ ViewContext.FormContext = new FormContext(); } @using (Html.BeginCollectionItem("SearchTerms")) { <div class="search-term-item"> @Html.HiddenFor(n => n.SearchTermID) <div class="editor-label"> @Html.LabelFor(n => n.Text,"Term") </div> <div class="editor-field"> @Html.EditorFor(n => n.Text) @Html.ValidationMessageFor(n => n.Text) </div> <a href="javascript:void(0);" class="remove-search-item" title="Remove">Remove</a> </div> }
你的主页:
<div class="editor-label"> @Html.LabelFor(model => model.Search.SearchTerms) </div> <div id="search-terms-container" class="editor-field"> @if (Model.SearchTerms != null && Model.SearchTerms.Any()) { foreach (var item in Model.SearchTerms) { @Html.Partial("_SearchTerm",item) } } </div> <a href="javascript:void(0);" id="add-search-item">Add</a>
你的JavaScript(jQuery)部分:
$(document).on('click','#add-search-term',function () { $.ajax({ url: '@Url.Action("GetTermItem")',cache: false,success: function (data) { var cl = $('#search-terms-container'); cl.append(data); var terms = cl.find('.search-term-item'); terms.last().hide().show('blind'); } }); return false; }); $(document).on('click','.remove-search-term',function () { $(this).closest('.search-term-item').hide('blind',function () { $(this).remove(); }); var cl = $('#search-terms-container'); var terms= cl.find('.search-term-item'); return false; });