【问题标题】:POST 500 (Internal Server Error) ajax,mvcPOST 500 (内部服务器错误) ajax,mvc
【发布时间】:2014-08-29 18:45:29
【问题描述】:

我有 ajax 请求将数据发送到我的控制器,它收集我的下拉列表的值

错误是

POST http://localhost:65070/form/create 500 (Internal Server Error) 

错误的响应是

The required anti-forgery form field "__RequestVerificationToken" is not present.

更新 我的表格

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Form</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FormName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FormName)
            @Html.ValidationMessageFor(model => model.FormName)
        </div>


        <div class="editor-label">
            @Html.LabelFor(model => model.MasterID, "MasterModule")
        </div>
        <div class="editor-field">
            @Html.DropDownList("MasterID", String.Empty)
            @Html.ValidationMessageFor(model => model.MasterID)
        </div>
        <select id="State" name="state"></select><br />
        <p>
            <input type="submit" value="Create" />
        </p>

    </fieldset>
}

我的ajax请求

$('#State').change(function () {
  var a = $('#State').val();
    $.ajax({
                url: "/form/create",
                type: "POST",
                data: { 'SubID': a },
                success: function (result) {
                    //        console.log(result);
                }
            });
        });

我的控制器

public ActionResult Create(Form form, int SubID)
        {
            if (ModelState.IsValid)
            {
                form.SubId =SubID;
                form.CreatedDate = DateTime.Now;
                form.CreatedBy = 1;
                form.CreatedDate = DateTime.Now;
                form.IsActive = true;
                form.ModifyBy = 1;
                form.ModifyDate = DateTime.Now;

                db.Forms.Add(form);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.MasterID = new SelectList(db.Departments, "MasterId", "ModuleName", form.MasterID);
            return View(form);
        }

它给出了 500 个内部错误.. 它的尴尬请帮助

【问题讨论】:

  • 该错误的响应是什么?
  • 回应?在没有得到
  • 有一个带有错误的响应...例如 500: no such method Create - 类似的东西。在控制台中打开您的网络选项卡并查看请求。
  • 路径创建/表单,方法发布,输入文本/html..这是红色的响应
  • 看起来您在 Create() 方法上有 [ValidateAntiForgeryToken] 属性。删除它或在 jquery 函数中传递值。为什么第一个参数是Form form?您没有传递任何值,因此它将为空。

标签: ajax asp.net-mvc


【解决方案1】:

您的 post 方法必须具有 [ValidateAntiForgeryToken] 属性。删除属性或在视图中添加标记

@Html.AntiForgeryToken()

并在ajax函数中传回

$('#State').change(function () {
  var a = $('#State').val();
  var token = $('[name=__RequestVerificationToken]').val();
  $.ajax({
    ....
    data: { __RequestVerificationToken: token, 'SubID': a },
    ....

注意form参数在action方法中不是必须的

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int SubID)
{
  ....

【讨论】:

  • 非常感谢!!我已经坚持了几个小时 D:
  • 这真的很有帮助。 :-)
【解决方案2】:

我有一个在我的应用程序中使用过的示例。在控制器中,你必须放置

[HttpPost]
[ValidateAntiForgeryToken]
    public JsonResult Verificar(int idempleado, string desde, string hasta)
     {
      ...
     return Json(suiche, JsonRequestBehavior.AllowGet);
     }

在视图中,我有一个ajax函数

    function Verificar(desde, hasta) {
        var token = $('[name=__RequestVerificationToken]').val();
        var empleadoId = parseInt($('#empleadoId').val());
        var url = '/Settlements/Verificar';
        var settings = {
            "async": true,
            "crossDomain": true,
            "url": url,
            "method": "POST",
            "data": { __RequestVerificationToken: token, idempleado: empleadoId, desde: desde, hasta: hasta, }
        }
        $.ajax(settings).done(function (response) {
            if (response) {
                $('#mensajefrom').text(null);
                $('#mensajeto').text(null);
            } else {
                $('#mensajefrom').text("There is another settlement with that date range");
                $('#mensajeto').text("There is another settlement with that date range");
            }
        });
    }

在表格中,我使用@Html.AntiForgeryToken()

【讨论】:

    猜你喜欢
    • 2020-12-11
    • 2017-10-14
    • 2018-10-10
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    相关资源
    最近更新 更多