Home > OS >  Cant post the data using Modal with Ajax in Razor Pages
Cant post the data using Modal with Ajax in Razor Pages

Time:01-07

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  id="btn1">Add Employee</button>

The Modal:

<!-- The Modal -->
<div >
    <div >
        <div >

            <!-- Modal Header -->
            <div >
                <h4 >Add Employee</h4>
                <button type="button"  data-bs-dismiss="modal"></button>
            </div>

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

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

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

The Js Code:

$("#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ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

CodePudding user response:

1.You maybe not familiar with Razor Pages, Razor pages uses OnGet and OnPost to deal with the Http Get and Post request. If you need another Get or Post method in current PageModel, you need define the method name like: OnGetHandlerName or OnPostHandlerName.

2.If your .cshtml.cs file located like: Pages/Employees/Index.cshtml.cs, the request url should be:/Employees/Index. If you set the handler in your PageModel, the request url should be:/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.

If you use form in Razor Pages, it will default generate an input with token. If not, you need add @Html.AntiForgeryToken() manually.

A whole working demo you could follow:

Page(Pages/Employees/Index.cshtml):

@page
@model IndexModel
<button  id="btn1">Add Employee</button>
<div >
    <div >
        <div >

            <!-- Modal Header -->
            <div >
                <h4 >Add Employee</h4>
                <button type="button"  data-bs-dismiss="modal"></button>
            </div>

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

            <!-- Modal footer -->
            <div >
                <button  onclick="AddEmployee();">Save</button> I
                <button  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:

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