在Ajax.BeginForm中传递UpdateTargetId而不替换目标

时间:2016-08-29 18:17:57

标签: jquery html ajax asp.net-mvc asp.net-web-api

在Ajax.BeginForm中,即使我已经指定了作为我的局部视图的targetId,它也正在替换整个视图。我错过了什么吗?

ProductList.cshtml

<div class="form-style-1" style="float:left">
           @using (Ajax.BeginForm("SearchProducts", "Product", new AjaxOptions()
           {
           HttpMethod="POST",
           InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace,
           UpdateTargetId = "product-list-container"
           }))
           {
           <form>
              <input name="SearchText" id="SearchText" class="field-divided" style="width: 300px;" type="text" />
              <input type="submit" value="Search" class="myButton" />
           </form>
           }
        </div>@Html.Partial("ListPartialView", Model)


ListPartialView.cshtml - 

<div id="product-list-container">
    @foreach (var product in Model)
    {
        <div class="product_box margin_r40">
            <div class="thumb_wrapper"><a><img src="@Url.Content(@product.ImagePath)" alt="image 1" /></a></div>
            <h3>@product.ProductName</h3>
            <p>@product.Description</p>
        </div>
    }
    <div class="button_01"><a href="#">View All</a></div>
    <div class="cleaner"></div>
</div>

SearchProducts - 控制器操作

[HttpPost]
        public ActionResult SearchProducts()
        {
            var searchTxt = Request.Form["SearchText"];                                                
            IEnumerable<Product> searchedProducts = (from p in dal.Products
                                                     where p.ProductName.Contains(searchTxt) ||
                                                     p.Description.Contains(searchTxt)
                                                     select p).ToList();

            return PartialView("ListPartialView", searchedProducts);
        }

1 个答案:

答案 0 :(得分:6)

确保您的页面/布局中包含jquery.unobtrusive-ajax.js

<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

此文件使您的表单变得灵活。

如果您没有包含此文件,您的表单将是普通表单。单击提交按钮将执行正常的表单提交,这可能是您查看整个页面的原因。