views:

273

answers:

2

i have an asp.net mvc website where i build up most of the page using C# for example building up html tables given a set of data from my viewmodel

i also have a lot of javascript that then dynamcially modifies these tables (add row for example).

the javascript code to add a new row looks extremely similar to my "rendering" code i have in C# that is used to build up the html table in the first place.

Every time i change the c# code to a add a new field, i have to remember to go back to the javascript code to do the same.

is there a better way here?

+8  A: 

One way to do this is to expose the logic that generates the markup as a web service on your server and have JavaScript get that markup via an AJAX call rather than duplicating the logic.

This way you can call something like a CreateRow method from JavaScript that will actually invoke the same exact logic that you used on the server when you rendered the page.

Andrew Hare
this is a great idea . . may be a little slow compared to having the code already on the client side but definately does that job of removing redundancy.
ooo
A: 

Look at Scott Gu's article: ASP.NET MVC 2: Model Validation

Basically, you define the validations at the model property level, and ASP.NET MVC 2 can automatically generate the proper client-side validation as well.

Unfortunately, this may mean you'll have to refactor everything into MVC, but a lot of ppl here would probably view that as a plus.

(disclaimer: I have not worked with ASP.NET MVC at all)

ZaijiaN
my code has nothing to do with duplicate validation.. its more building up html
ooo