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

时间:2018-04-01 16:58:37

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

作为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);
            });
        })

    })
}
);

控制器方法。到目前为止,我实际上已经失去了处理请求的方法。 Doint返回null。

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

        return Json(posted);
    }

我将非常感谢这项工作的指南。 谢谢

1 个答案:

答案 0 :(得分:0)

经过一些研究后,我解决了这个问题:

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帖子的服务器端端点

    [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的帮助

相关问题