简体   繁体   English

在客户端和服务器端都调用相同的方法

[英]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. 因此,我正在寻找一种可以在C#代码后面调用javascript函数的方法,或者可以满足需求的其他方法。 I thought about a service based function that I call it in client with ajax and in server as a simple function; 我想到了一个基于服务的函数,我在带Ajax的客户端和服务器中将其称为简单函数。 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). 使用ajax调用从控制器获取结果(仅服务器端计算)。
  • 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. 使用类似于Jint的Javascript解释器在服务器端执行同一段Javascript。

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. 例如,用于.NET的populair Java解释器可能是Jint ,它已经证明了其稳定性和性能。 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. 您可以在服务器上进行计算,然后将其发送回客户端以完成客户端上的其余操作,或者执行ajax调用(在客户端上显示加载面板)并返回带有结果的回调。

If you can provide more details, you will get better help. 如果您可以提供更多详细信息,则会获得更好的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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