从返回的视图中提取Div

时间:2013-03-28 06:55:24

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

我正在努力将视图从控制器返回到jquery,返回View但我想从返回的视图中提取div。我的当前代码是这样的

       public ActionResult DeleteItem(int pid)
                {
                 //my logic goes here
                    retutn View("SomeView",model);
                    }

                 Jquery


enter code here
          script type="text/javascript">
              $(document).ready(function () {

        $('.Remove').click(function () {
             var value = $(this).attr('id');
            $.ajax({
                cache:true,
                type: "POST",
                url: "@(Url.Action("DeleteItem", "ControllerName"))",
                data: "pid=" + value,
                success: function (data) {
                    $("body").html(data);

                },
                error:function (xhr, ajaxOptions, thrownError){
                    alert('Failed to subscribe.');

                }, 
                complete: function() {   } 
           });       
            return false;
                 });
                      });

        </script>

我当前的逻辑返回视图并将总视图分配,即html + body到页面的正文部分,它显示了两次html部分。有没有办法从返回的视图中检索div并重新加载它。 提前谢谢

2 个答案:

答案 0 :(得分:1)

您的控制器操作应返回PartialViewResult,否则它将返回响应中的布局页面。如果您想满足这两种情况,可以检查请求是否是AJAX请求:

public ActionResult DeleteItem(int id) {
    // delete your item

    if (Request.IsAjaxRequest()) {
        // return just the partial view
        return PartialView("yourview");
    }


    // otherwise handle normally
    return RedirectToAction("list");
}

要了解返回View和返回PartialView之间的区别,请参阅What's the difference between "return View()" and "return PartialView()"

答案 1 :(得分:0)

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

    $('.Remove').click(function () {
         var value = $(this).attr('id');
        $.ajax({
            cache:true,
            type: "POST",
            url: "@(Url.Action("DeleteItem", "ControllerName"))",
            data: "pid=" + value,
            success: function (data) {
                     var t=$(data).find('.divtoreplacewith');
                               $('.divtoreplace').replaceWith(d);
         //Wasted my 2 days for above two lines.But satisfied with solution,
          //Both div are same but '.divtoreplacewith' is having new data,And I have replaced div with that div that's all
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert('Failed to subscribe.');

            }, 
            complete: function() {   } 
       });       
        return false;
             });
                  });