简体   繁体   English

在Razor调用我的HTML Helper之前先调用Javascript函数

[英]Call Javascript Function before Razor calls my HTML Helper

I've been working on a HTML helper which will hide or show menu items depending on what type of user you are. 我一直在研究HTML帮助程序,该帮助程序将根据您是哪种类型的用户来隐藏或显示菜单项。

For this reason, In one of my controllers I am setting a session variables with values such as "ADMIN" 因此,在我的一个控制器中,我正在使用诸如“ ADMIN”之类的值设置会话变量

context.Session["perfil"] = "ADMIN"

The problem I am facing is that the Helper function is being called before the Javascript function which calls the controller that sets the session variables 我面临的问题是在调用设置会话变量的控制器的Javascript函数之前先调用Helper函数

This is how I call my HtmlHelper (through Razor) 这就是我叫我的HtmlHelper的方式(通过Razor)

 @using XSiteManagerWeb.Helpers
 @Html.Raw(Html.MiMenu("../Home/Configuracion", "Configuración"))

From my _Layout.cshtml 从我的_Layout.cshtml

But before doing that I'm calling the function 但在此之前,我先调用该函数

 <script type="text/javascript">ObtenerDatosSesion();</script>

Which calls a Controler method through Ajax 通过Ajax调用Controler方法

...
$.ajax({
        url: "../Home/ObtenerDatosSesion",
....

Question: Why is the HtmlHelper being called before ObtenerDatosSesion(); 问题:为什么在ObtenerDatosSesion();之前ObtenerDatosSesion(); HtmlHelper ObtenerDatosSesion(); even though I've put it before on the _Layout.cshtml ? 即使我之前将它放在_Layout.cshtml上?

I've also tried calling in on window load doing this: 我也尝试过在窗口加载中执行以下操作:

<body class="Fondoblue" onload="ObtenerDatosSesion();">

among other methods. 在其他方法中。

I noticed the Helper is being called before everytime after many debuggings. 我注意到在进行多次调试后,每次都会调用Helper。 What I can't figure out is why that happens. 我不知道为什么会这样。

I wonder if it has anything to do with the Web.config line one has to put to use html helpers 我想知道它是否与Web.config第1行必须使用html helper有关

<add namespace="XSiteManagerWeb.Helpers"/>

So to make it clear, I just want to make my "ObtenerDatosSesion(); method gets called before my html helper! 为了明确"ObtenerDatosSesion(); ,我只想让我的"ObtenerDatosSesion();方法在我的HTML帮助器之前被调用!

The razor helpers are executed server side, therefore they will be executed before any JS is rendered/executed on the page. 剃刀助手在服务器端执行,因此将在页面上呈现/执行任何JS 之前执行它们。

I would recommend moving whatever logic is in your ../Home/ObtenerDatosSesion endpoint to the same endpoint as ../Home/Configuracion . 我建议将../Home/ObtenerDatosSesion端点中的任何逻辑移动到与../Home/Configuracion相同的端点。 If it's going to be called more than once, you can put it in its own method. 如果要多次调用它,则可以将其放在自己的方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM