2015-04-15 34 views
0

我是asp.net MVC的新手。我的项目中有一张动态表格。在表中添加动态行与下面的链接在Asp.net mvc4剃刀视图中编辑和更新动态表中的行

Adding and deleting rows in dynamic table in Asp.net mvc razor view

我需要编辑和更新动态表的帮助下实现的。 我曾尝试下面的代码

我的样品模型

public class Gift 
{ 
    public string Name { get; set; } 
    public double Price { get; set; } 
} 

public class GiftViewModel 
{ 
    public string Age { get; set; } 
    public DateTime TheDate { get; set; } 
    public IEnumerable<Gift> Gifts { get; set; } 
} 

我的样品控制器

public class HomeController : Controller 
{ 
    [HttpGet] 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(GiftViewModel model) 
    {    
     // do work here 
     return RedirectToAction("Index"); 
    } 

    public ViewResult AddNew() 
    { 
     return View("_TimeSheetView"); 
    } 
} 

我的样品管窥

@model HelloWorldMvcApp.Gift 
@using (Html.BeginCollectionItem("giftList")) 
{ 
    <div> 
     <span class="drop_medium"> 
      @Html.TextBoxFor(m => m.Name) 
     </span> 
     <span class = "drop_medium"> 
      @Html.TextBoxFor(m => m.Price) 
     </span> 
    </div> 
} 

我的样本主视图

@model HelloWorldMvcApp.GiftViewModel 
@using (Html.BeginForm()) 
{ 
    @Html.TextBoxFor(m => m.Age) 
    @foreach (var data in Model.Gifts) 
    { 
     { Html.RenderPartial("_TimeSheetView", data); } 
    } 
    @Html.ActionLink("Add another", "AddNew", null, new { id="addItem" }) 
    <input type="submit" value="Save"/> 
} 

<script type="text/javascript"> 
    $("#addItem").click(function() { 
     $.ajax({ 
      url: this.href, 
      cache: false, 
      success: function (html) { $("#dynamic").append(html); } 
     }); 
     return false; 
    }); 
</script> 

当我点击'添加另一个'按钮时,一行被添加到表中。在编辑表格中的值之后当我单击提交按钮时,我在控制器中没有收到任何内容。 IEnumerable Gifts变量为null。如何将表格值传递给控制器​​。请帮我解决这个问题。在此先感谢

+1

你的模型属性被命名为''礼品所以它的需求是'Html.Begin CollectionItem(“Gifts”))'(不是'“giftlist”')。而且您还没有显示添加新项目的脚本。 –

+0

@StephenMuecke添加新行没有问题。我会改变你提到的代码,并让你知道 – mvm

+0

@StephenMuecke我像你所说的那样将“礼物列表”更改为“礼物”,但它没有奏效。我收到礼物为空 – mvm

回答

0

你的模型的集合属性被命名为Gifts所以部分需要是

@model HelloWorldMvcApp.Gift 
@using (Html.BeginCollectionItem("Gifts")) // not "giftlist" 
{ 
    ... 
} 

这将生成正确的名称输入用于绑定到一个集合属性(其中##Guid

<input name="Gifts[##].Name" ... /> 
<input name="Gifts[##].Price" ... /> 
<input type="hidden" name="Gifts.Index" value="##" /> 
0

您面临的问题是与您的模型结构匹配的渲染输入的名称。有一对夫妇的方式出这一点:

  1. 做一个编辑模板模型类型

你的部分观点:

@model IEnumerable<HelloWorldMvcApp.Gift> 
@Html.EditorForModel("","Gifts") 

和礼品模型的EditorTemplate:

@model HelloWorldMvcApp.Gift 
<div> 
    <span class="drop_medium"> 
     @Html.TextBoxFor(m => m.Name) 
    </span> 
    <span class = "drop_medium"> 
     @Html.TextBoxFor(m => m.Price) 
    </span> 
</div> 
  1. 手动创建te输入与正确解析的名称 - “Gifts [x] .Property”

显然,第一个选项是非常清洁和imho首选。

希望这个作品,并帮助:)

+0

这不会生成正确的前缀(在主视图中它需要为'@ Html.EditorFor(m => m.Gifts)',不会添加删除项目所需的'Gifts.Index'输入,并且不会允许用户动态添加新项目。 –