Here you have two points with different solutions, if your problem is the impersistence of the data after the postback of a control, this can be solved with ViewState
.
Now, objectively on the question of how to execute a code-behind method via Javascript, there is a cake recipe for this, but with a more restricted application, it would be necessary to create a static method defined as
[WebMethod]
, which in addition have a peculiar configuration for your operation, you will not be able to manipulate other ASP components of your page on the server side.
First, check that in your Site.Master, a <asp:ScriptManager>
component already exists, if the answer is yes, you only have to add the EnablePageMethods="true"
attribute
<form runat="server">
<asp:ScriptManager runat="server" EnablePageMethods="true">
<Scripts>
//...
</Scripts>
</asp:ScriptManager>
<!-- resto do conteúdo -->
</form>
Once you've done this, you can add% static% to validation in your aspx. Since this method does not have a connection with the rendered components on the screen, instead of a [WebMethod]
void
it will have a ValidarNif()
return and will receive an input parameter of type bool
.
[System.Web.Services.WebMethod]
public static bool ValidaNif(string nif)
{
//no lugar dessa linha você aplicará as suas regras
return string.IsNullOrWhiteSpace(nif);
}
If everything went well here, by rendering the page and accessing the browser console, you will notice that there is a string
object initialized, as well as a representation of your method with the following signature PegeMethods
Youcaninvokethismethodthrough'PageMethods',rememberingtoindicatethebasepath.
<scripttype="text/javascript">
PageMethods.set_path('/SuaPagina.aspx'); //Precisa ser definido apenas uma vez
PageMethods.ValidaNif('teste', //Valor que você vai capturar do TextBox
onSuccess = function(res){alert(res);},
onFailure = function(res){alert('error:' + res);}
);
</script>
If you receive an error message with status ValidaNif(nif, onSuccess, onFailure, userContext)
, in your project browse App_Start and edit the file 401 (Unauthorized)
by changing RouteConfig.cs
to AutoRedirectMode
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
settings.AutoRedirectMode = RedirectMode.Off;
routes.EnableFriendlyUrls(settings);
}
}