简体   繁体   English

无法在 Razor 页面中使用带有 Ajax 的模态发布数据

[英]Cant post the data using Modal with Ajax in Razor Pages

This is the index file code:这是索引文件代码:

 public IList<Employee> Employee { get; set; }

        public async Task OnGetAsync()
        {
            Employee = await _context.Employee.ToListAsync();
        }

        public JsonResult EmployeeList()
        {
            var data = _context.Employee.ToList();
            return new JsonResult(data);
        }

        [HttpPost]
        public JsonResult AddEmployee(Employee e)
        {
            var emp = new Employee()
            {
                Name = e.Name,
                Age = e.Age,
                Email = e.Email
            };
            _context.Employee.Add(emp);
            _context.SaveChanges();
            return new JsonResult("Success!!!");
        }

Button to open Modal:打开模态的按钮:

<button class="btn btn-info mb-3" id="btn1">Add Employee</button>

The Modal:模式:

<!-- The Modal -->
<div class="modal Add-Emp">
    <div class="modal-dialog">
        <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Add Employee</h4>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <!-- Modal body -->
            <div class="modal-body">
                <form method="post">
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" placeholder="Enter Name" class="form-control" id="Name" autocomplete="off"/>
                    </div>
                    <div class="form-group">
                        <label>Age</label>
                        <input type="text" placeholder="Enter Age" class="form-control" id="Age" autocomplete="off"/>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" placeholder="Enter Email" class="form-control" id="Email" autocomplete="off"/>
                    </div>
                </form>
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button class="btn btn-primary" onclick="AddEmployee();">Save</button> I
                <button class="btn btn-danger btn-default" data-bs-dismiss="modal">Close</button>
            </div>

        </div>
    </div>
</div>

The Js Code: Js代码:

$("#btn1").click(function () {
        $(".Add-Emp").modal("show")
    })
function AddEmployee() { debugger
            var objData = { Name: $("#Name").val(), Age: $("#Age").val(), Email: $("#Email").val() }

            $.ajax({
                url: "Pages/Employees/Index/AddEmployee",
                type: "Post",
                data: objData,
                contentType: "application/xxx-www-form-url-encoded; charset=utf-8",
                dataType: "json",
                success: function () { alert("Data Saved"); },
                error: function () { alert("Error!!!"); }
            })
        }

Modal opens on click But data does not get posted on clicking the save button it displays alert "Error!!!"单击时打开模态但是单击保存按钮时不会发布数据,它显示警报“错误!!!” defined in failure of ajax requestㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ定义在 ajax 请求失败ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

1.You maybe not familiar with Razor Pages, Razor pages uses OnGet and OnPost to deal with the Http Get and Post request. 1.你可能不熟悉Razor页面,Razor页面使用OnGetOnPost来处理Http的Get和Post请求。 If you need another Get or Post method in current PageModel, you need define the method name like: OnGet HandlerName or OnPost HandlerName.如果您需要在当前 PageModel 中使用其他 Get 或 Post 方法,则需要定义方法名称,例如: OnGet HandlerName 或OnPost HandlerName。

2.If your .cshtml.cs file located like: Pages/Employees/Index.cshtml.cs , the request url should be: /Employees/Index . 2.如果您的.cshtml.cs文件位于: Pages/Employees/Index.cshtml.cs ,请求 url 应该是: /Employees/Index If you set the handler in your PageModel, the request url should be: /Employees/Index?handler=xxx .如果您在 PageModel 中设置处理程序,请求 url 应该是: /Employees/Index?handler=xxx

3.For how to use Ajax in Razor Pages, Razor Pages enable anti-forgery token validation by default, so you need add this token to header in ajax. 3.关于Razor页面中Ajax的使用方法,Razor页面默认开启防伪token验证,所以需要在ajax中将此token添加到header中。

If you use form in Razor Pages, it will default generate an input with token.如果你在 Razor 页面中使用 form,它会默认生成一个带有 token 的输入。 If not, you need add @Html.AntiForgeryToken() manually.如果没有,您需要手动添加@Html.AntiForgeryToken()

A whole working demo you could follow:您可以遵循一个完整的工作演示:

Page(Pages/Employees/Index.cshtml):页面(Pages/Employees/Index.cshtml):

@page
@model IndexModel
<button class="btn btn-info mb-3" id="btn1">Add Employee</button>
<div class="modal Add-Emp">
    <div class="modal-dialog">
        <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Add Employee</h4>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <!-- Modal body -->
            <div class="modal-body">
                <form method="post">
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" placeholder="Enter Name" class="form-control" id="Name" autocomplete="off" />
                    </div>
                    <div class="form-group">
                        <label>Age</label>
                        <input type="text" placeholder="Enter Age" class="form-control" id="Age" autocomplete="off" />
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" placeholder="Enter Email" class="form-control" id="Email" autocomplete="off" />
                    </div>
                </form>
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button class="btn btn-primary" onclick="AddEmployee();">Save</button> I
                <button class="btn btn-danger btn-default" data-bs-dismiss="modal">Close</button>
            </div>

        </div>
    </div>
</div>

@section Scripts
{
    <script>
        $("#btn1").click(function () {
            $(".Add-Emp").modal("show")
        })
        function AddEmployee() {
            debugger
            var objData = { Name: $("#Name").val(), Age: $("#Age").val(), Email: $("#Email").val() }

            $.ajax({
                url: "/Employees/Index?handler=AddEmployee",
                type: "Post",
                data: JSON.stringify(objData), //change here...
                contentType: "application/json; charset=utf-8", //change here...
                headers: {
                    RequestVerificationToken:
                        $('input:hidden[name="__RequestVerificationToken"]').val()
                },   //add this....
                dataType: "json",
                success: function () { alert("Data Saved"); },
                error: function () { alert("Error!!!"); }
            })
        }
    </script>
}

Pages/Employees/Index.cshtml.cs:页面/员工/Index.cshtml.cs:

public class IndexModel : PageModel
{
    //...
    public IList<Employee> Employee { get; set; }

    public async Task OnGetAsync()
    {
        Employee = await _context.Employee.ToListAsync();
    }

    public JsonResult OnGetEmployeeList()
    {
        var data = _context.Employee.ToList();
        return new JsonResult(data);
    }

    public JsonResult OnPostAddEmployee([FromBody]Employee e)
    {
        var emp = new Employee()
        {
            Name = e.Name,
            Age = e.Age,
            Email = e.Email
        };
       
        return new JsonResult("Success!!!");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM