C# 在 MVC3 Razor 创建视图中动态添加表单元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11379958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically Add Form Elements in MVC3 Razor Create View
提问by J0NNY ZER0
I'd like to create a form with a group of text boxes and every time a user clicks the add button those text boxes will be recreated as many time as the user clicks the add button. Here is a picture of what I am looking to do.
我想创建一个带有一组文本框的表单,每次用户单击添加按钮时,这些文本框将在用户单击添加按钮时重新创建。这是我想要做的事情的图片。
Controller:
控制器:
//
// 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
创建.cshtml
@model MovinMyStuff.WebUI.Areas.Client.Models.CreateMoveViewModel
@using Telerik.Web.Mvc.UI
@{
ViewBag.Title = "Create";
}
<h1>Post a Move</h1>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="form-item-group last">
<div class="form-item half">
<div class="editor-label">
Start Date
</div>
Editorfor for Model1...
<div>
@Html.Partial("_MoveItem")
</div>
</fieldset>
<div class="submit-button-wrapper">
<input class="button" type="submit" value="Post" />
</div>
}
<div>
@Html.ActionLink("Go Back", "Index", null, new { @class = "link-text" })
</div>
ViewModel
视图模型
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; }
}
}
Partial View
局部视图
@model MovinMyStuff.Domain.Entities.MoveItem
<div class="editor-label">
Choose Area of Your Home
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MoveItemArea)
@Html.ValidationMessageFor(model => model.MoveItemArea)
</div>
<div class="editor-label">
Choose Your Item
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MoveItemType)
@Html.ValidationMessageFor(model => model.MoveItemType)
</div>
<div class="editor-label">
Quantity
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Quantity)
@Html.ValidationMessageFor(model => model.Quantity)
</div>
Other Properties of model...
<div class="editor-label">
@Html.HiddenFor(model => model.MoveId)
</div>
回答by Jorge
Well i will tried to create a partial View with the model that you need, The key will be to add the html generated from the partial view each time that click the button with ajax for example:
好吧,我将尝试使用您需要的模型创建一个局部视图,关键是在每次单击带有 ajax 的按钮时添加从局部视图生成的 html,例如:
Your model
你的模特
public class example
{
public int Length { get; set;}
public int Width { get; set;}
public int Height {get; set;}
}
Your Action
你的行动
public ActionResult Example()
{
return View();
}
Your Partial View
你的部分观点
@model FooExample.Model.Example
@{
Layout = null;
}
<div>
@Html.EditorFor(model => model.Length)
</div>
<div>
@Html.EditorFor(model => model.Width)
</div>
<div>
@Html.EditorFor(model => model.Height)
</div>
Your Principal View
你的主要观点
<input type="button" id="btnAddRows" />
<table id="addViews">
<tr>
<td>
</td>
</tr>
<table>
Now this is the script
现在这是脚本
$(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("<tr/><td>"+data+"</td><tr>");
}
})
});
});
回答by Pablo Romeo
Here's an explanation to how I've implemented similar situations in the past: https://stackoverflow.com/a/10583792/1373170
这是对我过去如何实施类似情况的解释:https: //stackoverflow.com/a/10583792/1373170
Its more complicated since it required to support editing and deleting as well.
The main idea is to have a hidden template (created with an EditorTemplate), used for creating new rows, and a bit of JavaScript to automatically name all new items to a way that will be automatically interpreted by MVC's default binder, and transformed to the appropriate List of ViewModels in the Action.
它更复杂,因为它也需要支持编辑和删除。主要思想是有一个隐藏模板(用 建立EditorTemplate),用于创建新行,以及一些 JavaScript 来自动命名所有新项目,以一种将由 MVC 的默认绑定器自动解释的方式,并转换为适当的动作中的 ViewModel 列表。
回答by Darin Dimitrov
I very strongly invite you to read the following article. It contains an example of how to achieve what you are looking for. It covers the challenges you will encounter with the default model binder when starting to implement this. To overcome those challenges with the collections indexes the author uses a custom Html.BeginCollectionItemhelper.
我强烈邀请您阅读以下文章。它包含一个示例,说明如何实现您正在寻找的目标。它涵盖了您在开始实施此默认模型绑定器时将遇到的挑战。为了克服集合索引的这些挑战,作者使用了自定义Html.BeginCollectionItem帮助程序。

