【问题标题】:Ajax calls to a web api methodAjax 调用 Web api 方法
【发布时间】:2015-08-24 12:13:56
【问题描述】:

我有这样的看法:

 <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>

有了它,我使用了这个脚本:

$(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;

    }
});
                           });

在控制器中我有这个方法:

  [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 };
            }

        }

问题是,如果我提交了表单,并且调试了代码,web api 方法在每次点击提交时都达到了 3 次!!我不明白这是为什么。我的 WebApiConfig 只是包含这个 sn-p :

 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}" 
       );
    }
}

所以我需要知道:

  1. 为什么会这样?
  2. 我该如何解决?

【问题讨论】:

  • 您是否尝试过使用 Fiddler 查看来自浏览器的请求数?

标签: c# jquery ajax asp.net-mvc asp.net-web-api


【解决方案1】:

第一个是从您的Ajax.BeginForm 调用的。

第二个是由您在此处手动连接按钮调用的:

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

第三个是因为您没有阻止上述点击功能中的默认提交。

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

快速解决方案可能是将您的AjaxBegin.Form 替换为Html.BeginForm 并阻止默认提交。然后你的点击函数会提交一次。

【讨论】:

    猜你喜欢
    • 2015-10-08
    • 2013-08-16
    • 2014-07-31
    • 2014-12-11
    • 2015-03-12
    • 2016-07-14
    • 1970-01-01
    • 2014-10-14
    • 2013-11-12
    相关资源
    最近更新 更多