使用 AJAX 的呼叫控制器

call controller using ajax

本文关键字:呼叫控制 控制器 呼叫 AJAX 使用      更新时间:2023-09-26

嘿,我想使用 ajax 调用控制器操作。 但它给出了一个错误。"找不到资源"。JavaScript 函数调用成功 控制器操作未调用

这是我的视图代码:

<a class="btn btn-primary" onclick="EditUser('Delete', 'Users', '@Model.Items.ElementAt(i).ID');">Link</a>

 function EditUser(action, controller, id)
            {
                alert(action);
                alert(controller);
                alert(id);
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("Edit", "Users")',
                    data: "{ id: '" + id + "'}",
                    success: function (response) {
                    if (response.d != '1') {
                        alert('Not Saved!');
                    }
                    },
                    error: function (response) {
                    if (response.responseText != "") {
                         alert(response.responseText);
                         alert("Some thing wrong..");
                       }
                   }
                 });
            }

这是我的控制器操作。

public override ActionResult Edit(int id = 0)
        {
    int a = id;
     return View("Edit", DTO);
    }
<div id='Sample'></div>
Modify your Ajax function as below.
$.ajax({
            type: "POST",
            url: '@Url.Action("Edit", "Users")',
            data: { id: id },
            success: function (response) {
            $('#Sample').html(response);
            },
            error: function (response) {
            if (response.responseText != "") {
                 alert(response.responseText);
                 alert("Some thing wrong..");
               }
           }
         });
[HttpPost]
public override ActionResult Edit(int id = 0)
    {
int a = id;
 return PartialView("Edit",dto);
}

如果要将 Ajax 类型指定为 post,请确保添加
[维基邮报]控制器操作中的属性。