简体   繁体   中英

Call same method both in client-side and server-side

I have a complex calculation in my page and I want to perform it in both client-side and server-side. For easier maintenance, I prefer to write one function and call it in client and server.

So I am searching for a method that I could call a javascript function in C# code behind or something else that could satisfy the demand. I thought about a service based function that I call it in client with ajax and in server as a simple function; however, it is obvious it would slightly work slowly in client because it should go to the server and come back.

Any idea?

As i stated in the comment, i can think of three options you have here.

  • Use an ajax call to get the result from the controller (server-side calculation only).
  • Use a postback, which pretty much does the same as the option above.
  • Use an Javascript interpreter like Jint, to execute the same piece of Javascript on the server side.

I think the first two are prefered, but the third option might be a solution if you really don't to do a call or postback. This will cause the client-side code to calculate it's own result, while server-side is able to do the same. Same code, Same result, No call from client-side to server-side.

A populair Javascript interpreter for .NET might be Jint for example, which has proven it's stability and performance. You might want to check it out.

You either do calculations on server and send them back to client to complete the rest on the client, or do an ajax call (show a loading panel on the client) and return for the callback with the results.

If you can provide more details, you will get better help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM