2015-10-05 32 views
-1

我从CSHTML文件在客户端使用jQuery或JavaScript与内容从模型动态添加行

<div id="trows" class="table-responsive"> 
     <table class="table table-bordered" id="myTable"> 
</div> 

和添加按钮事件中剪断下面的代码添加行我试图为以下: -

 var itemRSelected = $("#SelectedteRId option:selected").text(); 
     var itemNSelected = $("#SelectedName option:selected").text(); 

     debugger; 
     //all ok till above. I verified in debuggger 
     //but I am not able to add these values along with the Model rows to the table using below code. Any help? clue to fix the issue? 
     @{var i = 0;} 
     @foreach (MyNameSpace.Models.MyClassObj p in Model.myClassList) 
     { 
      if(itemRSelected == p.RowId && itemNSelected == p.NamePix) { 
          var row = "<tr><td>" + @(p.RowId) + "</td><td>" + @(p.NamePix) + 
       "</td><td>" + @(p.Mi) + "</td><td>" + @(p.Name) + 
       "</td><td>" + @(p.ExtraDate) + 
       "</td><td><a class='btn btn-danger btn-xs btnDelete' title='Delete'><i class='fa fa-trash-o'></i></a></td><tr>" ; } 

       @: <text>@row</text> 
       @:$("#myTable").eq(@i++).after(@row); 

      } 
+0

您__can't__使用__Client Side__ JavaScript变量'itemNSelected'当__SERVER Side__代码呈现逻辑即'如果(itemRSelected == p.RowId && itemNSelected = = p.NamePix)'。为什么不能使用jQuery Ajax实现它? – Satpal

+0

建议你看看答案[这里](http://stackoverflow.com/questions/29161481/post-a-form-array-without-successful/29161796#29161796)和[这里](http:// stackoverflow。 com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308)动态添加集合对象到视图 –

+0

@Satpal,我试图避免服务器之旅我希望在第一次查看旅程本身时,我可以在客户端拥有所有模型数据。 – AKS

回答

0

要使用该功能,你需要创建一个HTML表格,并给它一个唯一的ID。示例代码使用tblGrid作为ID,但您可以使用任何其他名称 - 只需确保修改该函数以使用新名称即可。接下来,您需要修改addRow函数以确保添加正确数量的单元格并正确设置其innerHTML。

//add a new row to the table 
function addRow() 
{ 
    //add a row to the rows collection and get a reference to the newly added row 
    var newRow = document.all("tblGrid").insertRow(); 

    //add 3 cells (<td>) to the new row and set the innerHTML to contain text boxes 

    var oCell = newRow.insertCell(); 
    oCell.innerHTML = "<input type='text' name='t1'>"; 

    oCell = newRow.insertCell(); 
    oCell.innerHTML = "<input type='text' name='t2'>"; 

    oCell = newRow.insertCell(); 
    oCell.innerHTML = "<input type='text' name='t3'>&nbsp;&nbsp;<input" + 
         " type='button' value='Delete' onclick='removeRow(this);'/>"; 
} 

//deletes the specified row from the table 
function removeRow(src) 
{ 
    /* src refers to the input button that was clicked. 
     to get a reference to the containing <tr> element, 
     get the parent of the parent (in this case <tr>) 
    */ 
    var oRow = src.parentElement.parentElement; 

    //once the row reference is obtained, delete it passing in its rowIndex 
    document.all("tblGrid").deleteRow(oRow.rowIndex); 

} 

,并且可以参考这个链接Dynamically add and remove rows in an HTML table

+0

@穆罕默德,谢谢它为表工作,但我需要调用ajax来获取行添加到表中。但你的回答帮助我解决问题,因此接受你的答案。谢谢。 – AKS