Pull a return from a JS function to C#

Asked

Viewed 83 times

0

In the user registration process I want to validate your CPF by Javascript and return if it is valid or not in beckend. And so make a if with this result to insert it into the database or not.

if (ValidaCpf(txtCpf.Text) == False){
    //retorna um erro
}

else{
   //cadastra o usuário
}

Note: I already have the function of validating the CPF and the method of Inserting the User in the BD. I just need to pass the result of the validation of Javascript to the C#.

  • 1

    Leave more information. Does this come from a form? How it is created?

  • You should not rely on javascript validation, you should always revalidate all data on the server, a malicious user can circumvent their javascript validations and send what they want to the server.

1 answer

0

This is a simple Jquery example for sending Cpf.

var cpf = 000000000000 
    $("button").click(function () { 
                $.ajax({ 
                    url: "/Home/PostJson", //local para onde vai ser enviado
                    type: "POST", //forma de envio
                    contentType: "application/json", 
                    data: '{cpf:cpf}', //informação enviada
                    success: function (data) { 
                        alert(data);
                    } 
                }); 
            }) 

Now looking at the application side

 public class HomeController : Controller 
    {          
        [HttpPost] 
        public JsonResult PostJson([FromBody] string cpf) 
        { 
           //faz a validação do cpf

           return Json(VarResultado, JsonRequestBehavior.AllowGet);
        } 
    } 

Sends the CPF via JSON to the application side, which does the validation and then returns the result to the screen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.