Dynamically add form elements to MVC3 Razor Create View

I would like to create a form with a group of text fields, and each time the user clicks the add button, these text fields will be recreated as many times as the user clicks the add button. Here is an image of what I'm looking for.enter image description here

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

@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>
+3
source share
3 answers

. , , . , , . , Html.BeginCollectionItem .

+6

, . , html, , ajax:

 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>

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

   });

});
+2

, : fooobar.com/questions/1909932/...

More complicated, as editing and deletion support is required. The basic idea is to have a hidden template (created with EditorTemplate) used to create new lines and some JavaScript to automatically detect all new elements in a way that will be automatically interpreted using the default MVC middleware and converted to the corresponding ViewModels list In action.

+1
source

All Articles