如何在mvc3中执行操作而不更改当前页面

How to execute action without change current page in mvc3

本文关键字:当前页 操作 mvc3 执行      更新时间:2023-09-26

我用Javascript yes no窗口让产品成为我的最爱。当点击"是"按钮时,产品将获得我的最爱并刷新背景页面。我在控制器中有MakeMyFavorite操作,但每次调用都返回相同的结果。

public ActionResult MakeMyFavorite( int id )
{
   ....
   return RedirectToAction( "Details", "Product", product );
}

和Javascript:

<script language="JavaScript" type="text/javascript">
    function confirmFavorite() {
        if (confirm("Are you sure make favorite?")) {
            document.location.reload(true);
            return true;
        } else {
            return false;
        }
    } 
</script>

和链接:

<a href="@Html.Action ( "MakeMyFavorite", "Product", new { id = item.ID } )" 
     onclick = "return confirmFavorite()"> Make Favorite </a> 

我在网站的不同位置使用制作收藏夹链接(详细信息、索引和其他视图)。单击链接时,产品是收藏夹,页面刷新,但始终打开"详细信息"视图。我在控制器中用void更改了ActionResult,但从未打开,因为没有返回视图。在网站的不同页面中,当我单击制作收藏夹链接时,产品是收藏夹,但背景页面不变,我该怎么办?保持当前视图。(抱歉英语不好)

您可以执行此

制作JsonResult操作

public JsonResult MakeMyFavorite(int id)
{
   ......
   string result = "favorite";
   return this.Json(result, JsonRequestBehavior.AllowGet);
}

使你的锚标签像

<a href="#" id="myfav" onclick="confirmFavorite(@item.id);">Favorite</a>

以及处理这个的jquery

<script type="text/javascript">
    function confirmFavorite (id) {
        if(confirm("Are you sure make favorite?")) {
           var data = { "id": id };
           $.getJSON("/Product/MakeMyFavorite", data, function (data) {
               //check your data here what it is returning
               if($.trim(data)=="favorite")
               {
                //Do what you want to do.
               }
           });
        }
     }
</script>

当您想要重新加载时传递一个值(true),当您不想要时传递(false或无参数):

<a href="@Html.Action ( "MakeMyFavorite", "Product", new { id = item.ID } )" 
 onclick = "return confirmFavorite( true )"> Make Favorite </a>
<a href="@Html.Action ( "MakeMyFavorite", "Product", new { id = item.ID } )" 
 onclick = "return confirmFavorite( false )"> Make Favorite </a>

然后在js:中

function confirmFavorite( reload ) {
    if (confirm("Are you sure make favorite?")) {
        if( reload ) {
            document.location.reload(true);
        }
        return true;
    } else {
        return false;
    }
}