2014-01-30 16 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