Search code examples
asp.netserver-tags

ASP.NET: Can you use server tags to embed C# or VB.NET expressions into a Javascript function?


I have an enum called SiteTypes that contains several values that are all bound to a dropdown list. On the client side, I need to check this dropdown to see if the selected value is one of those enum values. I don't want to hardcode the value of the enum in the script in case it needs to change, so I want to use a server tag to get it directly from the enum itself. Conecptually, I would like to do this:

function SiteIdChanged() {
    var x = "<%=SiteTypes.Employee %>";
}

The way I am doing it now is created a protected property in the codebehind that returns that specific enum value and am doing this:

function SiteIdChanged() {
    var x = "<%=EmployeeSiteTypeValue %>";
}

I don't like that, though, because I have to create a special property on every page that I need to do such a check.

Is there a way to do what I want here?


Solution

  • Are you getting a "xxx is inaccessible due to its protection level" error when you compile or run the page? enums are public by default, classes are not. My guess is that you've defined your enum inside your page's class and you aren't explicitly marking it with the 'public' access modifier. Explicitly mark it as public or move it outside of the class and see what happens. If you're planning on using it on lots of pages you should stick the enum definition in in a file in the App_Code folder of your project.