Gaurav Chauhan

Gaurav Chauhan

  • NA
  • 21
  • 645

How to add dynamic items to view?

Apr 13 2016 7:32 AM
I need to add a dropdown dynamically and get the values at post method. I am using asp.net MVC and visual studio 2013 community edition.
 
I have following view model.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BillingApplication.Models;

namespace BillingApplication.ViewModels
{
public class BillItem
{
public Bill Bill { get; set; }
public IEnumerable<Item> Item { get; set; }
}
}
 
and a view has following razor code.
 
<div class="unique">
<div class="form-group">
@Html.LabelFor(Model => Model.Item, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Item", null, htmlAttributes: new { @class = "form-control drop" })
</div>
</div>
</div>
 
 Now i need above drop down in view and user can add as many drop down as they want. so i have following javascript.
 
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {

var i = 1;
$(".unique").find(".drop").attr("name", "Item[0].ItemId");
$(".unique").find(".drop").attr("id", "Item[0].ItemId");

$("#plus").on('click', function () {
var clone2 = $('.unique').clone();
$(clone2).find(".drop").attr("name", "Item[" + i + "].ItemId ");
$(clone2).find(".drop").attr("id", "Item[" + i + "].ItemId");
$('.unique').after(clone2);
i++;
});
});
</script>
 
 This java script does the job and adds drop down on a click of the button. Now that is fine at view side. I am unable to get all the values at post back. All i get is the first value. Rest all the values are null. Why? 
I get Item[0].ItemID as the id of selected drop down,
I get Item[1].ItemID is null, Item[2].ItemID is null and so on.
 
How to get all the values... 
 
 
 

Answers (7)