POST 500(内部服务器错误)ajax,mvc

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25574410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:26:00  来源:igfitidea点击:

POST 500 (Internal Server Error) ajax,mvc

ajaxasp.net-mvc

提问by Jot Dhaliwal

I have ajax request that sends data to my controller , it collects value of my dropdown

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

the error is

错误是

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

response of error is

错误响应是

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

UPDATEMy Form

更新我的表格

@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>
}

My ajax Request

我的ajax请求

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

My controller

我的控制器

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

It is giving 500 internal error.. its awkward plz help

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

回答by

Your post method must have the [ValidateAntiForgeryToken]attribute. Either remove the attribute or in the view, add the token

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

@Html.AntiForgeryToken()

and pass it back in the ajax function

并将其传递回 ajax 函数中

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

Note the formparameter is not necessary in the action method

注意formaction方法中不需要参数

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

回答by Antonio Franceskin

I have an example that I have used in my applications. In the controller, you must place

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

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

In the view, I have an ajax function

在视图中,我有一个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");
            }
        });
    }

in the form, I use @Html.AntiForgeryToken()

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