【问题标题】:Make Ajax call before page loads在页面加载之前进行 Ajax 调用
【发布时间】:2013-05-13 16:12:41
【问题描述】:

在页面加载之前,我需要检查用户的安全级别。这将决定他们能够看到我们导航栏的哪些元素。我尝试了两种方法来运行这个 ajax 调用,都在 $(document).ready 函数中。

(名为containerdiv 包含下面html 中的ul

$(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();            
}

这应该是检查用户的安全级别,将boolean的值放在ViewBag中,然后判断是否显示下面的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

非常感谢任何帮助/建议。谢谢!

【问题讨论】:

  • 你有一个带有id="container"的元素吗?那个元素甚至有加载事件吗? (只有 iframe 图像脚本和窗口有加载事件)。不过第二次尝试应该会奏效。

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


【解决方案1】:

/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
}

因此,您可以返回一个列表。

【讨论】:

  • 所以基本上你正在使用的任何控制器/方法都是需要设置ViewBag的那个?
  • 我仍然很好奇为什么 Ajax 没有被解雇。有什么想法吗?
  • 我没有看到任何 html 中的元素的 id 为 container。你确定选择器$(#container) 选择了任何元素吗?
  • 确保 CheckSecurity 操作结果也在 HomeController 中。看看这个帖子,这可能会导致问题stackoverflow.com/questions/11767911/…
  • 它在HomeController 中。奇怪的是,由于这是一个共享布局页面,当您加载站点的 home/index.cshtml 页面时,Ajax 实际上会触发。但是,导航到站点中的任何其他位置(所有页面都使用相同的布局和导航栏/ajax 代码)并且不会调用该方法。
猜你喜欢
  • 2014-10-30
  • 2014-06-21
  • 1970-01-01
  • 2016-11-21
  • 2019-11-28
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
相关资源
最近更新 更多