简体   繁体   中英

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

I am submitting json model through ajax post. 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]属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM