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

StackOverflow https://stackoverflow.com/questions/7907835

  •  14-02-2021
  •  | 
  •  

Question

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?

Was it helpful?

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.

OTHER TIPS

If you don't like your current implementation I would consider using a PageMethod to compare the dropdown selection to the enum value. This approach will probably be cleaner, as you can do most of the logic server-side.

Here's a tutorial on PageMethods:
http://blogs.microsoft.co.il/blogs/gilf/archive/2008/10/04/asp-net-ajax-pagemethods.aspx

As long as your enum is marked public, you can just go with your first option. There's no need to put a property on every single page you want to retrieve the value from.

That approach is really the simplest solution for writing out server side values in your JavaScript.

You can use the Enum.IsDefined Method this well tell you if the selected value from the dropdown is actually part of your enum.

Enum.IsDefined(typeof(MyEnum), myValue)

http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top