如何在MVC 3视图中获取JS中的模型项数据?

时间:2013-03-26 10:48:14

标签: jquery asp.net-mvc asp.net-mvc-3

我正在开发一个MVC应用程序。 我在索引视图/表中显示数据。

我在最后一栏添加了额外的复选框。 当用户单击该复选框时,我希望从所选/已检查行的特定列中获取值。

我试图在JS的警报窗口中显示该值,但它没有显示。

如何做到这一点。

 @model PagedList.IPagedList<PaymentAdviceEntity.PaymentAdvice>

            <table class="table table-striped">
                <tr>
                    <th>Company
                    </th>
                    <th>
                       Amount
                    </th>
               </tr>

         @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.Company.Name)
                        </td>
                        <td>
                             @Html.DisplayFor(modelItem => item.SanctionedAmount,"sAmount","sAmount")
                        </td>
                        <td>

    @Html.CheckBox("IsPaid", (bool)item.IsPaid, new { @value=item.Id,@class="IsPaid-"+item.Id})

                   </td>
                    </tr>
    </table>

<script type="text/javascript">

           $("input[type='checkbox']").click(function () {

                if ($(this).is(":checked"))
                {
                    var nPaid = $("#sAmount").val();
                    alert(nPaid);
                }

               });
        </script>   

1 个答案:

答案 0 :(得分:4)

您应该将js代码包装到文档就绪。

    <script type="text/javascript">
       $(function(){
         //TO DO smt
         });
       });
    </script>

您需要在id中使用不同的foreach。例如

 @Html.DisplayFor(modelItem => item.SanctionedAmount, string.Format("sAmount{0}", item.Id),"sAmount")

或使用$(this).parent ...

更改jquery选择器

所有代码都是:

  @model PagedList.IPagedList<PaymentAdviceEntity.PaymentAdvice>

        <table class="table table-striped">
            <tr>
                <th>Company
                </th>
                <th>
                   Amount
                </th>
           </tr>

     @foreach (var item in Model)
            {
                <tr>


                    <td>
                        @Html.DisplayFor(modelItem => item.Company.Name)
                    </td>

                    <td>
                         @Html.DisplayFor(modelItem => item.SanctionedAmount,"sAmount",new {id = string.Format("sAmount{0}", item.Id)})
                    </td>


                    <td>

@Html.CheckBox("IsPaid", (bool)item.IsPaid, new { @value=item.Id,@class="IsPaid-"+item.Id})


                 </td>
                </tr>
</table>


<script type="text/javascript">
$(function() {
    $("input[type='checkbox']").click(function () {
        if ($(this).is(":checked")) {
            var v = parseInt($(this).val(), 10);
            var s = 1;
            var nPaid = $("#sAmount" + v).val();
            alert(nPaid);
        }
    });
})