嵌套的部分视图调用HttpPost方法2次

时间:2016-03-06 10:13:54

标签: ajax asp.net-mvc asp.net-mvc-4 partial-views

我在这里几次被问过这个问题,但我看到的解决方案并不通用,它们与具体代码有关..

我需要纠正以前的开发人员完成的工作,代码中的ajax调用流是错误的

在我的情况下,我有以下观点:

1.Index (Main View)
2.ParentCategoryList (partial View inside Index)
3. AddChild (partial View inside ParentCategoryList )
4. childCategorytree  (Seperate View )

问题是来自第二个嵌套视图(AddChild),当我点击保存按钮时,httpost方法正在调用两次

我的索引视图

<div>

            <div class="content" id="divparent">
            </div>

            <div class="content" id="dvChild">
            </div>


</div>

其脚本

@section scripts{


    <script type="text/javascript">
        $('document').ready(function () {


            //------------
            $.get('@Url.Action("ParentCategoryList", "List")', function (data) {
                $("#divparent").html("");
                $("#divparent").html(data);

            });

        })



        function addnewchild(url) {

            $.get(url, function (data) {
                $("#dvChild").html("");
                $("#dvChild").html(data);

            });
        }


    </script>

}
  1. 索引内的第一部分视图(ParentCategoryList.cshtml)

        @foreach (Bmsa.UI.Models.ListsResultModel  data in Model)
        {
            <tr> <td><a onclick="addnewchild('@Url.Action("AddChild",   
        "List", new { id = @data.listID })')" >
                    </a> </td></tr> }  </tbody> </table>
    
  2. ParentCategoryList中的第二个嵌套部分视图

     @using (Ajax.BeginForm("AddChild", "List", new AjaxOptions
    {
    
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "dvChild"
    }))
            {
            <div > <input type="submit" value="Save" /></p></div>}
    
  3. 和控制器方法

        public ActionResult ParentCategoryList()
         {
            //Code 
            return PartialView("ParentCategoryList", categoryList); }
    

    //获取加载此视图的操作

          public ActionResult AddChild(int id)
          {
            ViewBag.ParentID = id;
            ListsAddModel addchild = new ListsAddModel();
            addchild.parentListId = id;
            return PartialView("AddChild", addchild);
          }
    
    
      [HttpPost] (**this method is calling twice--this is the problem** )
        public ActionResult AddChild(ListsAddModel model,int id)
        {
    
       //Code
            return RedirectToAction ("ChildCategoryListTree", new { id = model.parentListId });
        }
    
    1. 和childCategorytree部分视图(也是空白)
    2. 我无法阻止此方法调用两次。我在$ .ajax调用中尝试了e.preventDefault(),但它无效...

      我试过最小化代码,我认为问题出在RedirectToAction中,但我不确定

      任何帮助将不胜感激

0 个答案:

没有答案
相关问题