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

时间:2012-07-08 01:15:04

标签: c# asp.net-mvc-3

我想创建一个包含一组文本框的表单,每次用户单击“添加”按钮时,这些文本框将在用户单击“添加”按钮时重新创建。这是我要做的事情的照片。enter image description here

控制器:

    //
    // 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";
}

<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>

视图模型

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

    <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>

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

我将尝试使用您需要的模型创建部分视图,关键是每次单击带有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;
 }

<div>
     @Html.EditorFor(model => model.Length)  
</div>
<div>
     @Html.EditorFor(model => model.Width)  
</div>
<div>
     @Html.EditorFor(model => model.Height)  
</div>

您的校长视图

<input type="button" id="btnAddRows" />

<table id="addViews">
     <tr>
        <td>
        </td> 
     </tr>
<table>

现在这是脚本

$(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>");
           }  
       })

   });

});

答案 2 :(得分:1)

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

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