Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Ajax calls to a web api method

I have this view :

 <div id="addDisplay" class="display">
                <div class="box-header">
                    <h3 class="box-title">Ajouter un compte</h3>
                </div>
                @{
                    AjaxOptions addAjaxOpts = new AjaxOptions
                    {
                        // options will go here
                        OnSuccess = "getData", 
                        OnFailure="selectView('add')",
                        HttpMethod = "Post",
                        Url = "/api/AccountManage/CreateAccount"
                    };
                }
                @using (Ajax.BeginForm(addAjaxOpts))
                {

                @Html.Hidden("id", 0)
                <p>
                    <label>Statut social   </label>
                    <select id="marital_status" name="marital_status">
                        <option value="Mr">Monsieur</option>
                        <option value="MLLE">Mademoiselle</option>
                        <option value="MME">Madame</option>
                    </select>



                </p>
                <p><label>Nom   </label>@Html.Editor("Nom")<label style="color:red" id="labError"> ( * )</label></p>
                <p><label>Prenom   </label>@Html.Editor("Prenom")<label style="color:red" id="labError"> ( * )</label></p>
                <p><label>Adresse   </label>@Html.TextArea("address")<label style="color:red" id="labError"> ( * )</label></p>
                <p><label>Pseudo   </label>@Html.Editor("Username")<label style="color:red" id="labError"> ( * )</label></p>
                <p><label>Email   </label>@Html.Editor("Email")<label style="color:red" id="labError">Entrer une adresse mail valide</label></p>
                <p><label>Mot de passe   </label>@Html.Editor("Password")<label style="color:red" id="labError">Doit contenir au moins une lettre majuscule, une minuscule, un chiffre et un caractère spécial</label></p>
                <p>
                    <label>Rôle</label>
                    <select id="Role" name="Role">
                        <option value="adminpark">Administrateur Park</option>
                        <option value="chauffeur">Chauffeur</option>
                        @if (User.IsInRole("admin") || User.IsInRole("manager") || User.IsInRole("superadmin"))
                            {
                            <option value="employe">Employé</option>
                                if (User.IsInRole("superadmin"))
                                {
                            <option value="admin">Administrateur</option>
                            <option value="manager">Manager</option>
                                }
                            }
                    </select>

                </p>

                  <button type="submit" class="btn btn-primary" id="AddNew">Enregistrer</button>
                  <button type="button" class="btn bg-maroon btn-flat margin" id="Annuler">Annuler</button>

                }
            </div>

with it, I used this script :

$(document).ready(function () { 
selectView("summary");
getData();
$("button").click(function (e) {


    var selectedRadio = $('input:radio:checked')

    switch (e.target.id) {

        case "refresh":
            getData();
            break;

        case "delete":
            $.ajax({
                type: "Delete",
                url: "/api/AccountManage/DeleteAccount/" + selectedRadio.attr('value'),
                success: function (data) {
                    selectedRadio.closest('tr').remove();
                }
            });
            break;


           case "add":
               selectView("add");
               $('#Nom').val("");
               $('#Prenom').val("");
               $('#adress').val("");
               $('#Username').val("");
               $('#Email').val("");
               $('#Password').val("");

            break;


        case "edit":          
            $.ajax({
                type: "GET",
                url: "/api/AccountManage/GetCollaborator/" + selectedRadio.attr('value'),
                success: function (data) {
                    $('#editid').val(data.id);
                    $('#editiduser').val(data.id_user_fk);
                    $('#editNom').val(data.Nom);
                    $('#editPrenom').val(data.Prenom);
                    $('#editAdresse').val(data.address);
                    selectView("edit");
                }
            });
            break;

        case "submitEdit":
            $.ajax({
                type: "PUT",
                url: "/api/AccountManage/UpdateAccount/" + selectedRadio.attr('value'),
                data: $('#editForm').serialize(),
                success: function (result) {
                    if (result) {
                        var cells = selectedRadio.closest('tr').children(); 
                        cells[1].innerText = $('#editNom').val();
                        cells[2].innerText = $('#editPrenom').val(); 
                        cells[3].innerText = $('#Role').val(); 
                        selectView("summary");
                    }
                },
                error:  selectView("edit")
            });
            break;

        case "Annuler":
            selectView("summary");
            break;

    }
});
                           });

In the controller I have this method :

  [HttpPost]
        public System.Web.Mvc.JsonResult CreateAccount(CollaborateurModel item)
        {

            var user = new ApplicationUser { UserName = item.Username, Email = item.Email };
            if (UserManager.FindByEmail(item.Email) == null) 
            {
                var result = UserManager.CreateAsync(user, item.Password).Result;
            } 

            if(ModelState.IsValid)
            {
                var currentUser = UserManager.FindByName(item.Username);
                var roleresult = UserManager.AddToRole(currentUser.Id, item.Role);
                ajt_collaborator entity = Mapper.Map<CollaborateurModel, ajt_collaborator>(item);
                entity.id_user_fk = currentUser.Id;
                entity.is_deleted = false; 
                repo.CreateCollaborator(entity);
                return new System.Web.Mvc.JsonResult { Data = true };
            }

            else
            {
                return new System.Web.Mvc.JsonResult { Data = false };
            }

        }

The problem is that if I submitted the form, and debug the code the web api method were reached three times in every click of submit!! I dont understand the reason of this. My WebApiConfig is just contain this snippet :

 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{action}/{id}",
         defaults: new { id = RouteParameter.Optional }
       );

        config.Routes.MapHttpRoute(
           name: "DefaultApi2",
           routeTemplate: "api/{controller}" 
       );
    }
}

So I need to know :

  1. Why this happens?
  2. How can I fix it?

Upvotes: 2

Views: 326

Answers (1)

hutchonoid
hutchonoid

Reputation: 33306

The first one is called from your Ajax.BeginForm.

The second one is called from you manually wiring up the button here:

$("button").click(function (e)

The third one will be because you are not preventing the default submit in your above click function.

$("button").click(function (e)
 e.preventDefault();

The quickes solution will probably be to replace your AjaxBegin.Form with an Html.BeginForm and prevent the default submit. Then your click function will submit it once.

Upvotes: 5

Related Questions