如何通过 Ajax 到 c# asp.net 核心控制器方法 POST 表单

How to POST a form via Ajax to c# asp.net core controller method

作为 ASP.NET Core 的新手,这是我第一次尝试使用 jquery 对 asp.net 控制器方法进行 ajax 调用,我找到了它难的。下面是我的视图表单、我的 javascript 文件和我的控制器方法;

查看表单

<form id="components-form">
                @Html.AntiForgeryToken();
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="entryformLabel">Payment Entries</h4>
                </div>
                <div class="modal-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover table-striped" id="list-table">
                            <thead>
                                <tr>
                                    <th>Entry</th>
                                    <th>Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var ent in ViewBag.staffEntries)
                                {
                        <tr>
                            <th>@ent.EntryLabel</th>
                            <th><input type="text" class="form-control entry" name="component[@ent.EntryId]" id="@ent.EntryId" value="@ent.EntryValue" /></th>
                        </tr>
                                }
                            </tbody>
                        </table>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" id="update-entries-btn" class="btn btn-success"><span class="fa fa-check"></span> Update Entries</button>
                </div>
            </form>

Javascript 文件

$(document).ready(function ()
{
    var updateBtn = $("#update-entries-btn").click(function ()
    {
        $("#update-entries-btn").click(function () {
            var token = $("[name=__RequestVerificationToken").val();

            var postedValues = new FormData();
                postedValues.append("__RequestVerificationToken", token);


            $(".entry").each(function () {
                var id = this.id;
                var val = this.val;

                postedValues.append(id,val);
            });


            var postUrl = "/staff/updatecomponents";
            $.post(postUrl, postedValues, function (result) {
                alert(result);
            });
        })

    })
}
);

控制器方法。此时我实际上迷失了如何处理请求。将此 returns 设为空。

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult updatecomponents(string posted)
    {

        return Json(posted);
    }

我将不胜感激获得此工作的指南。 谢谢

经过更多研究,我这样解决了这个问题:

Javascript代码

$(document).ready(function ()
{
    $("#update-components-btn").click(function ()
    {
        var token = $("[name=__RequestVerificationToken").val();

        var staffId = $("[name=staffId").val();

        var postedValues = {};

        postedValues["__RequestVerificationToken"] = token;

        postedValues.StaffId = staffId;

        postedValues.StaffComponents = [];

        $(".entry").each(function ()
        {
            var component = {};

            component.StaffId = staffId;

            component.EntryId = $(this).attr('id');

            component.ValueAmount = Number($(this).val());

            postedValues.StaffComponents.push(component);
        });

        var postUrl = "/staff/updatecomponents";

        $.post(postUrl, postedValues, function (result)
        {
            var report = JSON.parse(JSON.stringify(result));

            if (report.status)
            {
                swal("<span class=fa fa-thumbs-up", report.message, "success");
                setInterval(function () { window.location.reload(true); }, 5000);
            }
            else
            {
                swal("<span class=fa fa-thumbs-down", report.message, "error");
            }
        });
    });
}
);

我必须创建一个模型来模拟预期的对象

 public class StaffEntryUpdateModel
{
    public string RequestToken { get; set; }
    public string StaffId { get; set; }
    public List<StaffEntry> StaffComponents { get; set; }
}

最后是接收和处理 ajax post

的服务器端端点
    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult updatecomponents(StaffEntryUpdateModel postedData)
    {
        try
        {
            if (postedData.StaffComponents.Any())
            {
                ApplicationUser Staff = db.Users.FirstOrDefault(s => s.Id == postedData.StaffId);
                if (Staff == null)
                {
                    return new JsonResult(new { Status = false, Message = "Unknown staff" });
                }
                db.StaffEntries.Where(se => se.StaffId == postedData.StaffId).Delete();
                foreach (var c in postedData.StaffComponents)
                {
                    db.StaffEntries.Add(c);
                }

                int inserted = db.SaveChanges();

                return new JsonResult(new { Status = (inserted > 0) ? true : false, Message = inserted + " components updated for staff" });
            }
            else
            {
                return new JsonResult(new { Status = false, Message = "No component sent for update for staff" });
            }
        }
        catch (Exception e)
        {
            return new JsonResult(new {Status=false,Message=e.Message.ToString() });
        }
    }

在工作和审查代码的过程中,我不得不更改它在原始问题中出现的方式的一些项目,但它基本上是一样的。

我希望这可以帮助随时寻找此类解决方案的人。

感谢@Chetan Ranpariya 的帮助