Check Record in BD (ASP.NET MVC 5)

0

I would like you to help me to create a method that validates if there is already a record in BD with the name of the user that is authenticated and that this one returns a Boolean and sends it to the view to be used with JavaScript.

These DropDownList are saved with Ajax and stored correctly. As the user can only select and save those DropDown only once, what I want is that the next time the user enters the system, validate if this user already has 'Propositos' saved by means of a Boolean and allows me to do other things.

Thus stored in the database, the UserCode is stored from a Hidden type input.

The only thing I need is that the database was consulted by sending as a parameter the UserCode and if there is something already, that the created method returns a Boolean and passes it to the view to work it.

How can I do it? Thanks!

    
asked by Mateo Castaño Tobon 04.07.2018 в 15:54
source

2 answers

0

As you talk about it, you can create a method that returns a Boolean and consume it with jQuery Ajax.
The method in MVC would be something like this:

public bool TienePropositos(string correo)
{
    using(var bd = new Context())
    {
        return bd.Propositos.Any(x => x.CorreoUsuario == correo);
    }
}

Using jQuery you can consume as follows:

<script type="text/javascript">
    $(function () {
        $("#btnGet").click(function () {
            $.ajax({
                type: "POST",
                url: "/CONTROLLER/TienePropositos",
                data: '{correo: "'+$('#hidden_input')+'"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });
</script>
    
answered by 04.07.2018 в 16:22
0

You could create a rule in the database, so as not to make a query every time you save. A UK Composed of [Internal_Proposition_Id], [External_Proposition_Id], [UserMail] Seria

ALTER TABLE TuTabla
ADD CONSTRAINT  [UQ_Regla] UNIQUE NONCLUSTERED
    (
        [Proposito_Interno_Id], [Proposito_Externo_Id], [CorreoUsuario]
    )

With this, how much you try to insert in your table will return an Exception, which you could catch and send your message Something like:

    try
{
   // Tu INSERT
}
catch(SqlException ex)
{
   if(ex.Number == 2627)
   {
      //Envias el mensaje de claves duplicadas-
   }
}
    
answered by 04.07.2018 в 16:30