0

There are times when we use same error or success message/checking of some status both in jquery & c#.

For consistency, we can define all message/status flag in as static class and use it wherever needed in c#.

Just an example:

C#

public class MyConstant
{
   public static string Admin = "AdminRole";
   public static string Approver= "ApproverRole";
}
if(userRole==MyConstant.Admin || userRole==MyConstant.Approver)
{
   //more work
}

jquery:

if(userRole=="AdminRole" || userRole=="ApproverRole")
{
   //more work
}

In stead hard coding msg/status in jquery, I would prefer approach similar to C#. Would be better to have common place to pull for client/service side.

How can I achieve similar in jquery? Better to say, How can I share common msgs/status flags between jquery & C#. I can think of following options:

  1. Use Database. Cons: hitting DB every time may not be good idea.

  2. Define some classes/property for msgs/status flags separately in jquery. Cons: duplicate; have to ensure all of them in sync.

  3. maybe CMS but not necessarily, will be used in every application

Is there any better approach to share common Message/Error/Status to used across jquery or C#?

Thoughts?

user1480864
  • 1,455
  • 3
  • 16
  • 23

2 Answers2

2

One possible solution is T4 (text templates).

Just imagine a T4 which iterates each enumeration value (why classes of constants? use enumerations!) and creates an object literal like this in JavaScript:

var Roles = { "AdminRole": 1, "ApproverRole": 2 };

If you've never heard about T4, it's the text templating engine behind Visual Studio templates. For example, Entity Framework uses it to generate model classes.

Once you've created the text template, you can sync C# enumeration to JavaScript object literal from Visual Studio when you build your project or running the template manually (right-click on T4 and choose "Run custom tool").

Learn more about T4

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0

I would consider enums for status codes, but you can stay with your strings (no problem). To better address JavaScript part use solution presented here: https://stackoverflow.com/a/2383215/3170952, that is:

my.namespace.Roles = {
    ADMIN: "Admin",
    APPROVER: "Approver"
}

Then you have one place where you define literals in JS. Better yet, you can weave C# literals into your JS (if you define it in one of ASP.NET MVC views or have other mechanism of incorporating C# into JS files). Then you have one place of definition statically checked during compilation time.

Community
  • 1
  • 1
Marcin Wachulski
  • 567
  • 4
  • 14