在foreach循环中部分查看MVC 4

时间:2013-12-23 08:18:13

标签: asp.net-mvc asp.net-mvc-4

我正在使用 MVC 4 Ajax.BeginForm进行更新,但它只更新第一个元素<div>

视图:

@model List<CSP1225.Models.Item>
@{
    ViewBag.Title = "RecentItems";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="~/CSS/jobs.css" rel="stylesheet" />


@{ var convert = ViewBag.convert;
}
<div>

    @foreach (var item in Model)
    {
        <div class="job-item">
            <div class="inner">
                <div class="span8 job-span">
                    <!--start of job list container div-->
                    <div id="ja-joblist">
                        <ol id="ja-searchjoblist">

                            <li class="job-item">@{ var PriceLE = @item.Price * convert;}
                                @using (@Ajax.BeginForm("_AddToCart", "Home", item, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "cart" }, null))
                                {

                                    <!-- job item right section-->
                                    <div class="inner">
                                        <div class="ja-job-meta clearfix">
                                            <span class="ja-job-category"><a href="@item.ItemURL" target="_blank">@item.ItemName</a></span>
                                            <span class="ja-job-category">@item.Price $</span>
                                            <span class="ja-job-category">@PriceLE LE</span>
                                            <div id="cart"></div>

                                            <button type="submit">Add to Cart</button>

                                        </div>
                                    </div>
                                } </li>

                            <!-- end of job item right section-->





                            <!-- end of job item -->

                        </ol>

                    </div>
                </div>
            </div>
        </div>
    }
    @Html.ActionLink("Go Back", "Index", "Home", new { @class = "makeneworder" })

</div>

和控制器:

 public ActionResult _AddToCart(Item model)
      {
          ItemModel it = new ItemModel();
          it.itemName = model.ItemName;
          it.itemUrl = model.ItemURL;
          it.quantity = 1;
          it.unitprice = model.Price;
          it.weight = (int)model.Weight;
          it.ItemCategory =(int)model.CategoryID;

          CartList.Add(it);
          ViewBag.convert = (decimal)_db.Currencies.Where(x => x.Name == "Dollar").FirstOrDefault().Value;
          ViewBag.list = CartList;
          return PartialView();

      }     

部分观点:

<p>Added to Cart</p>

但视图返回多个元素(只要列表包含元素)当我点击添加到购物车时它会更新第一个元素..我理解,因为你不能给另一个{{1相同的ID,但我该如何解决?

1 个答案:

答案 0 :(得分:0)

您可以创建一个动态ID,如

@{ var divID = 1; }

然后像

一样使用它
UpdateTargetId = "cart" + divID }

 <div id="cart@divID"  ></div>