简体   繁体   English

Ajax使用反伪造令牌将JSON模型发布到ASP.Net MVC4

[英]Ajax post a JSON model to ASP.Net MVC4 with Anti-forgery token

I am submitting json model through ajax post. 我正在通过ajax发布提交json模型。 Its not working after adding user validation. 添加用户验证后,它不起作用。

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

Controller : 控制器:

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

View: 视图:

@using (Html.BeginForm())
{

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

The server return 服务器返回

What could be missing in my method. 我的方法中可能缺少什么。 Please advice.... 请指教....

Attribute selectors should only have a single set of quotes around them. 属性选择器周围应该只有一组引号。 Your code has two quotes on each side. 您的代码两边都有两个引号。

This: 这个:

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

should be this: 应该是这样的:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用防伪令牌将JSON模型发布到ASP.Net MVC3 - Posting a JSON model to ASP.Net MVC3 with Anti-forgery token 如何在mvc中使用防伪令牌制作ajax请求 - How to make ajax request with anti-forgery token in mvc asp.net mvc“所需的防伪表单字段”__ RequestVerificationToken“不存在。” - asp.net mvc “The required anti-forgery form field”__RequestVerificationToken“ is not present.” 通过AJAX发布时,MVC防伪令牌不允许上传多个文件 - MVC Anti-forgery Token won't allow multiple file upload when posting through AJAX 反伪造令牌和Ajax JSON.stringify发布不起作用 - Anti Forgery Token and Ajax JSON.stringify Post Does not Work 带有asp .net核心的防伪令牌jquery ajax - Anti forgery token jquery ajax with asp .net core 使用CORS预检OPTIONS请求的Ajax防伪POST(302重定向) - Ajax anti-forgery POST with CORS preflight OPTIONS request (302 redirect) ASP.NET MVC4:在更改文本时,执行ajax请求,然后返回json结果并更新模型,而无需重新加载页面 - ASP.NET MVC4: On text changed, do ajax request, then return json result and update model without reloading page 反伪造令牌作为标头字段还是AJAX上的发布值? - Anti forgery token as header field or as Post value on AJAX? $ .post上没有必填的防伪表单字段“ __RequestVerificationToken” - The required anti-forgery form field “__RequestVerificationToken” is not present on $.post
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM