How to strongly type properties in JavaScript that map to models in C# ?

Posted by Roberto Sebestyen on Stack Overflow See other posts from Stack Overflow or by Roberto Sebestyen
Published on 2010-04-07T18:24:04Z Indexed on 2010/04/07 18:33 UTC
Read the original article Hit count: 146

Filed under:
|
|

I'm not even sure if I worded the question right, but I'll try and explain as clearly as possible with an example:

In the following example scenario:

1) Take a class such as this:

public class foo
{
   public string firstName {get;set;}
   public string lastName {get;set}
}

2) Serialize that into JSON, pass it over the wire to the Browser.

3) Browser de-serializes this and turns the JSON into a JavaScript object so that you can then access the properties like this:

var foo = deSerialize("*******the JSON from above**************");
alert(foo.firstName);
alert(foo.lastName);

What if now a new developer comes along working on this project decides that firstName is no longer a suitable property name. Lets say they use ReSharper to rename this property, since ReSharper does a pretty good job at finding (almost) all the references to the property and renaming them appropriately.

However ReSharper will not be able to rename the references within the JavaScript code (#3) since it has no way of knowing that these also really mean the same thing. Which means the programmer is left with the responsibility of manually finding these references and renaming those too.

The risk is that if this is forgotten, no one will know about this error until someone tests that part of the code, or worse, slip through to the customer.


Back to the actual question: I have been trying to think of a solution to this to some how strongly type these property names when used in javascript, so that a tool like ReSharper can successfully rename ALL usages of the property?

Here is what I have been thinking for example (This would obviously not work unless i make some kind of static properties)

var foo = deSerialize("*******the JSON from above**************");
alert(foo.<%=foo.firstName.GetPropertyName()%>)
alert(foo.<%=foo.lastName.GetPropertyName()%>)

But that is obviously not practical. Does anyone have any thoughts on this?
Thanks, and kudos to all of the talented people answering questions on this site.

© Stack Overflow or respective owner

Related posts about c#

Related posts about resharper