2014-01-30 17 views
0

我很多時候已經解決了這種情況,但還沒有找到好的方法。 MVC中的網頁我有:動態地添加了新的元素塊

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

然後頁面上我想點擊「+」按鈕,添加另一對標籤和按鈕。

這樣做的最佳方法是什麼?

注意:

沒有綁定的問題。

+0

我的合作工人採用淘汰賽JS http://knockoutjs.com/像這樣的東西 –

回答

1

這裏去我的PartialViews答案。解決這個問題的方法還有很多,比如使用簡單的客戶端jquery(不需要訪問服務器動作)。我建議你也去探索這些解決方案。

模型 -

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

控制器 -

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

索引視圖 -

@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管窺 -

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

輸出,當我們點擊+符號 -

enter image description here