如何使用model中的值初始化按钮的id

时间:2015-01-08 06:18:54

标签: linq asp.net-mvc-4

我正在使用List检索值列表,我正在使用for循环。要求在这里我有两个按钮,一个用于提交,另一个用于删除记录。当我单击btnDelete按钮时,我想删除该特定记录。

I am having the object Product as
public partial class Product
{
    public int Id { get; set; }
    public string Model_Name { get; set; }        
    public Nullable<int> Price { get; set; }
    public Nullable<int> Total_Products { get; set; }
}

现在我希望产品的属性ID出现在按钮的Id中,这样我就可以检索完整的记录并使用Jquery将其删除。我在这里完成了jquery我只想用模型中的值来分配按钮的Id。 我有以下代码

@model List<Shop_Online.com.Models.Product>
<script type="text/javascript">
//some script here
</script>
@using (Html.BeginForm())
{
<div style="width: 860px; margin: 0 auto" class="main">
    <table border="1" style="font-family: Verdana; font-size: 13px" class="table">
        <tr style="background-color: #f2f2f2; height: 30px">
            <th colspan="4">ITEM</th>
            <th>DELIEVERY DETAILS</th>
            <th>QTY</th>
            <th>SUB TOTAL</th>
            <th>Remove Items</th>
        </tr>
        <tbody>
@for(int i=0;i<Model.Count;i++)
{
<tr>      
    @Html.HiddenFor(x=>x[i].Id)
    <td colspan="4" > @Html.DisplayFor(x=>x[i].Model_Name)</td>
    <td style="width: 39%">Free Delievery Delivered in 2-3 business days.</td>
    <td>@Html.TextBoxFor(x=>x[i].Total_Products)</td>
    <td>@Html.DisplayFor(x=>x[i].Price)</td>
    <td>
    //something like this
    //btnDelete
        <button type="submit" class="btnDelete"  value="x[i].Id" id="x[i].Id" 
        name="Action">Remove</button></td>
    </tr>
    }
    </tbody>
    </table>
    <input type="submit" value="Submit" id="btnPost"/>
    </div>
    }
  If I use foreach loop then I have

 @foreach(var item in model) then I can use the following within block as
 <button type="submit" class="remove" value="@item.Id" id="@item.Id" 
 name="Action">Remove</button>

由于

1 个答案:

答案 0 :(得分:0)

正如@Mark Shechenko已经写道:

<button type="submit" class="btnDelete" value="@Model[i].Id" id="@Model[i].Id" name="Action">Remove</button>

但是......如果Id是一个数字,您必须记住html中有ID和NAME属性的规则,请参阅此问题的答案:What are valid values for the id attribute in HTML?