2013-05-13 121 views
0

在加載頁面之前,我需要對用戶的安全級別進行檢查。這將決定他們能夠看到我們的導航欄的哪些元素。我在運行這個ajax調用時嘗試了兩種方法,都在$(document).ready函數中。在頁面加載之前進行Ajax調用

(在div命名container涵蓋ul在下面的HTML)

$(document).ready(function ($) { 
    //First attempt 
    $('#container').load(
     $.ajax({ 
      type: 'GET', 
      url: '@Url.Action("CheckSecurity","Home")' 
     }) 
    ); 

    //Second attempt 
    window.onload = function() { 
     $.ajax({ 
      type: 'GET', 
      url: '@Url.Action("CheckSecurity","Home")' 
     }); 
    }; 
}); 

因爲這是一個ASP MVC 3網站,我給自己定的CheckSecurity方法斷點。我可以告訴這兩個電話都不起作用,因爲它從未被解僱。

控制器方法如下

public ActionResult CheckSecurity() 
{ 
    ViewBag.UserName = Security.GetUserName(User); 
    ViewBag.Admin = Security.IsAdmin(User); 
    ViewBag.ITsupport = Security.IsItSupport(User); 
    ViewBag.Read = Security.IsViewer(User); 
    ViewBag.Modify = Security.IsModifier(User); 
    return View();    
} 

這應該檢查用戶的安全級別,放置在ViewBag的boolean值,然後確定是否要顯示所述Admin Features下拉項的下面

列出

<li class="dropdown"> 
    <a href="#" 
     class="dropdown-toggle" 
     data-toggle="dropdown" 
     data-hover="dropdown"> 
     Admin 
     <b class="caret"></b> 
    </a> 
    <ul class="dropdown-menu"> 
     <li>@Html.MenuLink("Products", "Index", "Product")</li> 
     <li>@Html.MenuLink("Product Training", "Index", "Course")</li> 
     <li>@Html.MenuLink("Continuing Ed", "Index", "ContEdCourse")</li> 
     @if (ViewBag.Admin) 
     { 
      <li>@Html.MenuLink("Admin Features", "Index", "DropDownValues")</li>    
     } 
    </ul> 
</li> 

當網頁嘗試加載,它不是與指向@if (ViewBag.Admin)線這個錯誤崩潰

Cannot convert null to 'bool' because it is a non-nullable value type

任何幫助/建議非常感謝。謝謝!

+0

你有一個'id =「container」'元素嗎?並且這個元素是否有負載事件? (只有iframes圖像腳本和窗口有加載事件)。第二次嘗試應該已經工作了。 – 2013-05-13 18:24:02

回答

0

/ViewBags只是在相同的視圖工作。這意味着這樣的:

如果你在

public ActionResult Index() 
{ 
    ViewBag.Index 
} 

,然後你通過AJAX

public ActionResult OtherAction() 
{ 
    ViewBag.Other 
} 

執行的ViewBag.Other不會在指數可見

public ActionResult Index() 
{ 
    ViewBag.Index 
    ViewBag.Other//erro other is null cuz because bellows to OtherAction view 
} 

所以,你可以返回一個列表。

+0

所以,基本上無論你使用哪種控制器/方法,都需要設置ViewBag? – NealR 2013-05-13 16:24:06

+0

我仍然好奇爲什麼Ajax沒有被解僱。有關於此的任何想法? – NealR 2013-05-13 16:26:52

+0

我沒有看到任何HTML,你有一個id爲'container'的元素。你確定選擇器'$(#容器)'選擇任何元素嗎? – 2013-05-13 16:31:32