2016-08-25 29 views
1

這是ASP.NET MVC項目,我已將div放置在頁面中的特定位置並添加了標識dealProductAnchor。當這個頁面正常加載或重新加載時,它的行爲是正常的,但是當點擊一個特定的按鈕時當頁面加載完成時,我需要完成所有的回發進程,它來到該div的位置。如何在頁面重新加載MVC時在特定位置滾動頁面ASP.NET

與Java腳本我嘗試這樣做,但什麼也沒做,從服務器端或客戶端的任何解決方案將是明顯的。

$(".button-1").click(function() { 
     if (localStorage && !localStorage.getItem('click')) { 
      localStorage.setItem('click', true); 
     } 
    }); 


$(document).ready(function() { 
    if (localStorage.getItem('click') == true) { 

     window.location = window.location.href + "#dealProductAnchor"; 
     //click = false; 
    } 
    }); 

回答

1

如果你想要實現這個經由後端網絡,你可以設置一個值ViewBag並檢查它.cshtml頁面如下圖所示:

控制器代碼:

public ActionResult TextAction() { 
// Do your Logic here 
     ViewBag.testValue = "test"; 
     return View(); 
    } 

JavaScript代碼:

$(document).ready(function() { 
@if (ViewBag.testValue == "test") { 
     <text>$('html,body').animate({ 
      scrollTop: ($("#dealProductAnchor").offset().top) - 200 
     }, 'slow');</text> 
    } 
}); 

希望它可以幫助你:)

+0

後的位置,當我訪問該網頁,這將帶給我的所有時間,點擊按鈕時,我只想。我不會點擊,每次 – user6594294

+0

確定,那麼你可以跳過'$(文件)。就緒(函數(){$ ()觸發( 「點擊 」)「 按鈕-1」; });'此塊。之後,當你點擊button-1時,頁面將滾動到perticular div。 –

+0

當我點擊一個按鈕時,它執行一些後端操作並重新加載頁面,當重新加載完成後,我想要那個位置。上述代碼會在頁面加載之前帶我到那裏 – user6594294

0

你可以試試嗎?

$(".button-1").click(function() { 
$('html, body').animate({ 
     scrollTop: $("#dealProductAnchor").offset().top 
    }, 2000); 

}); 
+0

這將在頁面加載之前給我,我想網頁加載 – user6594294

0

,而不是設置的:

window.location = window.location.href + "#dealProductAnchor"; 

在你$(document).ready回調,使用Javascript設置scrollTop的:

$(document).ready(function() { 
    if (localStorage.getItem('click') == true) { 
     $('body').scrollTop($("#dealProductAnchor").offset().top) 
     localStorage.removeItem('click'); 
    } 
}); 

如果不工作,你可能需要添加一個window.setTimeout()包裝來讓瀏覽器完成呈現:

$(document).ready(function() { 
    if (localStorage.getItem('click') == true) { 
     window.setTimeout(function() { 
      $('body').scrollTop($("#dealProductAnchor").offset().top); 
     }); 
     localStorage.removeItem('click'); 
    } 
}); 
+0

都嘗試過。在控制檯中,click設置爲true,但是當$(document).ready(function()'調用啓動時,它不會進入if塊,即使localStorage爲真 – user6594294

+1

Ahh ... wait,getItem總是一個字符串!你的檢查應該是:localStorage.getItem('click')==「true」 – Robba

0

我會嘗試改變形式action屬性包括散列

$(".button-1").click(function() { 
    //Change $("form") to use the form ID if you have one 
    $("form").attr("action", $("form").attr("action") + "#dealProductAnchor"); 
} 

如果按鈕提交表單,你可能需要更改從提交按鈕按鈕,然後提交表單單擊處理程序。