Proceso a seguir para poder invocar código C# desde JavaScript sin tener que realizar PostBack.
1. Inicialmente tenemos que descargar Ajax del sitio web http://www.ajaxpro.info/.
2. Creamos una referencia al fichero .dll de Ajax que acabamos de descargar, en nuestro proyecto.
3. Preparamos un namespace.
[AjaxPro.AjaxNamespace("NombreDelNamespace")]
public partial class clase_de_ejemplo : System.Web.UI.UserControl ...
...
4. Introducimos la siguiente sentencia en el winform_load:
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(clase_de_ejemplo));
}
5. Creamos un método de prueba en nuestro win form C# de la siguiente manera:
[AjaxPro.AjaxMethod()]
public string SumaValores(int firstNumber, int secondNumber)
{
System.Threading.Thread.Sleep(3 * 1000);
return ("La suma de los valores " + firstNumber.ToString() + " y " + secondNumber.ToString() + " es igual a " + (firstNumber + secondNumber));
}
6. Creamos la función JavaScript que recogerá el valor de dicho método C#:
<script type="text/javascript">
function SumaValores_CallBack(response)
{
if (response.error != null)
{
alert("Los valores introducidos no son válidos.");
return;
}
target="contenido";
document.getElementById(target).innerHTML = response.value;
document.getElementById('cargando').innerHTML='';
}
</script>
7. Colocamos el botón en nuestro código html, con el código para llamar a la función C#:
<input onclick="document.getElementById('cargando').innerHTML='cargando';Ejemplo.SumaValores(TextBox1.value,TextBox2.value, SumaValores_CallBack);" type="button" value="Traer Datos">
8. En este ejemplo además tenemos una capa que nos muestra que estamos cargando datos mientras se realiza el proceso. Dicha capa es la siguiente:
<div id="cargando" style="left: 1px; position: absolute; top: 1px; font-weight: bold; color: white; background-color: red;"></div>
9. Modificar web.config con el siguiente código:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="ajaxNet">
<section name="ajaxSettings" type="AjaxPro.AjaxSettingsSectionHandler,AjaxPro.2" requirePermission="false" restartOnExternalChanges="true"/>
</sectionGroup>
</configSections>
<ajaxNet>
<ajaxSettings>
<urlNamespaceMappings useAssemblyQualifiedName="false" allowListOnly="false">
</urlNamespaceMappings>
<jsonConverters>
</jsonConverters>
<debug enabled="false"/>
<token enabled="false" sitePassword="password"/>
</ajaxSettings>
</ajaxNet>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true"/>
<authentication mode="Windows"/>
</system.web>
<location path="ajaxpro">
<system.web>
<httpHandlers>
<add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</httpHandlers>
</system.web>
</location>
</configuration>
Os dejo una lista de enlaces que me han sido de ayuda para realizar el tutorial.