1

我正在通过 ajax 帖子提交 json 模型。添加用户验证后它不起作用。

    var token = $('input[name=""__RequestVerificationToken""]').val();
    var headers = {};
    headers['__RequestVerificationToken'] = token;

        $.ajax({
            url: '/SalesQuotation/Create',
            cache: false,
            headers: headers,
            data: JSON.stringify(salesquotation),
            type: 'POST',
            contentType: 'application/json;',
            dataType: 'json',
            async: false,
            success: function (result) {
                if (result.Success == "1") {
                   window.location.href = "/SalesQuotation/Create";
                }
                else {
                    alert(result.ex);
                }
            }
         });

控制器 :

   [HttpPost]
   [ValidateAntiForgeryToken]
   public JsonResult Create(SalesQuotation salesquotation)
    {
        try
        {
            if (ModelState.IsValid)
            {
                if (salesquotation.QuotationId > 0)
                {

                    var CurrentsalesQuotationSUb = db.SalesQuotationSubs.Where(p => p.QuotationId == salesquotation.QuotationId);
                    foreach (SalesQuotationSub ss in CurrentsalesQuotationSUb)
                        db.SalesQuotationSubs.Remove(ss);

                    var CurrentsalesQuotationDta = db.DTATrans.Where(p => p.QuotationId == salesquotation.QuotationId);
                    foreach (DTATran ss in CurrentsalesQuotationDta)
                        db.DTATrans.Remove(ss);

                    foreach (SalesQuotationSub ss in salesquotation.salesquotationsubs)
                        db.SalesQuotationSubs.Add(ss);

                    foreach (DTATran ss in salesquotation.dtatrans)
                        db.DTATrans.Add(ss);

                    db.Entry(salesquotation).State = EntityState.Modified;
                }
                else
                {
                    db.SalesQuotations.Add(salesquotation);
                }

                db.SaveChanges();
            }
        }

        catch (Exception ex)
        {
            return Json(new { Success = 0, ex = "Unable to save... " + ex.Message.ToString()});
        }
       return Json(new { Success = 1, ex = new Exception("Saved successfully.").Message.ToString() });
    }

看法:

@using (Html.BeginForm())
{

    @Html.ValidationSummary(true)
    <input name="__RequestVerificationToken" type="hidden"          
    value="H4zpQFvPdmEdGCLsFgeByj0xg+BODBjIMvtSl5anoNaOfX4V69Pt1OvnjIbZuYrpgzWxWHIjbng==" />

服务器返回

我的方法中可能缺少什么。请指教....

4

2 回答 2

0

属性选择器应该只有一组引号。您的代码每边都有两个引号。

这个:

var token = $('input[name=""__RequestVerificationToken""]').val();

应该是这样的:

var token = $('input[name="__RequestVerificationToken"]').val();
于 2013-10-11T07:40:55.653 回答
0

在动作方法中使用[ValidateJsonAntiForgeryToken]属性。

于 2018-05-07T13:28:27.383 回答