在MVC3 Razor创建视图中动态添加表单元素

我想创建一个包含一组文本框的表单,每次用户单击添加按钮时,这些文本框将在用户单击添加按钮时重新创建。 这是我要做的事情的照片。 在此处输入图像描述

控制器:

// // GET: /Client/MyMove/Create public ActionResult Create() { return View(); } // // POST: /Client/MyMove/Create [HttpPost] public ActionResult Create(Move move) { var viewModel = new CreateMoveViewModel(); MembershipUser currentUser = Membership.GetUser(); Guid currentUserId = (Guid)currentUser.ProviderUserKey; if (ModelState.IsValid) { move.UserId = currentUserId; db.Moves.Add(move); move.AddMoveItem(2); db.SaveChanges(); return RedirectToAction("Index"); } return View(move); } 

Create.cshtml

 @model MovinMyStuff.WebUI.Areas.Client.Models.CreateMoveViewModel @using Telerik.Web.Mvc.UI @{ ViewBag.Title = "Create"; } 

Post a Move

@using (Html.BeginForm()) { @Html.ValidationSummary(true)
Start Date
Editorfor for Model1...
@Html.Partial("_MoveItem")
}
@Html.ActionLink("Go Back", "Index", null, new { @class = "link-text" })

视图模型

 namespace MovinMyStuff.WebUI.Areas.Client.Models { public class CreateMoveViewModel { public CreateMoveViewModel() { Moves = new Move(); MoveItems = new MoveItem(); } public Move Moves { get; set; } public MoveItem MoveItems { get; set; } } } 

部分视图

 @model MovinMyStuff.Domain.Entities.MoveItem 
Choose Area of Your Home
@Html.EditorFor(model => model.MoveItemArea) @Html.ValidationMessageFor(model => model.MoveItemArea)
Choose Your Item
@Html.EditorFor(model => model.MoveItemType) @Html.ValidationMessageFor(model => model.MoveItemType)
Quantity
@Html.EditorFor(model => model.Quantity) @Html.ValidationMessageFor(model => model.Quantity)
Other Properties of model...
@Html.HiddenFor(model => model.MoveId)

我非常强烈地邀请您阅读以下文章 。 它包含了如何实现您正在寻找的内容的示例。 它涵盖了在开始实现此操作时您将遇到的默认模型绑定器所遇到的挑战。 为了克服集合索引的这些挑战,作者使用自定义的Html.BeginCollectionItem帮助器。

好吧,我将尝试使用您需要的模型创建局部视图,关键是每次单击带有ajax的按钮时添加从局部视图生成的html:

你的模特

  public class example { public int Length { get; set;} public int Width { get; set;} public int Height {get; set;} } 

你的行动

 public ActionResult Example() { return View(); } 

你的部分观点

 @model FooExample.Model.Example @{ Layout = null; } 
@Html.EditorFor(model => model.Length)
@Html.EditorFor(model => model.Width)
@Html.EditorFor(model => model.Height)

你的主要观点

  

现在这是脚本

 $(document).ready(function(){ $("#btnAddRows").click(function(){ $.ajax({ url: 'your path to the action' data : 'if you need to pass parameters' datatype: 'html', success: function(data){ $("#addViews").append(""+data+""); } }) }); }); 

以下是我过去如何实施类似情况的解释: https : //stackoverflow.com/a/10583792/1373170

它更复杂,因为它也需要支持编辑和删除。 主要思想是使用隐藏模板(使用EditorTemplate创建),用于创建新行,以及一些JavaScript自动将所有新项目命名为将由MVC的默认绑定器自动解释的方式,并转换为适当的Action中的ViewModel列表。