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?

Note:

There isn't problem with binding.

Answers


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 = "a.microsoft.com" });
        sn.SubSiteNames.Add(new SubSite() { Name = "b.microsoft.com" });
        return View(sn);
    }

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

Index View -

@model MVC.Controllers.Site

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

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

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

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

_SubSite Partial View -

@model MVC.Controllers.SubSite

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

        <dd>
            @Html.TextBoxFor(model => model.Name)
        </dd>

    </dl>
</div>

Output, When we click on + Sign -


JQuery is perfect for this sort of thing.

http://learn.jquery.com/javascript-101/getting-started/


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.