Added new block of elements dynamicily

I have solved this situation many time,but haven't found good way yet. In mvc page I have:

    @for (int i = 1; i <= 2; i++)
        <label>Label @i </label>
        @Html.TextBoxFor(m => m.SubSiteNames[i - 1])
        <br />
    <input type="button" value="+"  />

Then on page I want to click '+' button and add another pair of label and button.

What is the best way to do it?


There isn't problem with binding.


Here goes my answer with PartialViews. There are many other ways to solve this problem, like using plainly client-side jquery (with out hitting server action). I would recommend you to explore those solutions too.

Models -

public class Site
    public List<SubSite> SubSiteNames { get; set; }
public class SubSite
    public string Name { get; set; }

Controller -

public class TableController : Controller
    public ActionResult Index()
        Site sn = new Site();
        sn.SubSiteNames = new List<SubSite>();
        sn.SubSiteNames.Add(new SubSite() { Name = "" });
        sn.SubSiteNames.Add(new SubSite() { Name = "" });
        return View(sn);

    public ActionResult SubSite()
        return PartialView("_SubSite");

Index View -

@model MVC.Controllers.Site

    ViewBag.Title = "Index";


<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    $(function () {
        $("#ClickMe").click(function () {
                url: "@Url.Action("SubSite")",
                type: "GET",
                error: function (response) {
                    if (!response.Success)
                success: function (response) {

<div id="content">
    @foreach (var item in Model.SubSiteNames)
        @Html.Partial("_SubSite", item);

<input type="button" value="+" id="ClickMe" />

_SubSite Partial View -

@model MVC.Controllers.SubSite

    <dl class="dl-horizontal">
            @Html.DisplayNameFor(model => model.Name)

            @Html.TextBoxFor(model => model.Name)


Output, When we click on + Sign -

JQuery is perfect for this sort of thing.

Need Your Help

Regular expression validate form

php regex forms validation

I can not figure out how can I put 5 characters that has a-z, A-Z, 0-9, and can include $ and @ with regex. This is what I have

How to save pdf in proper encoding via nodejs

node.js pdf encoding utf-8

So I'm trying to download a pdf file from a website with my script but the problem is that the file gets broken in the process and I'm pretty sure it's because of wrong encoding being used.