没有用ajax post mvc4插入

时间:2013-08-28 06:38:35

标签: jquery ajax asp.net-mvc-4

即使我对值进行硬编码,也没有插入任何内容。我可以使用在创建Transaction类时创建的方法,还是必须为ajax调用编写自定义方法?

jQuery / ajax call

$("#SubmitTransaction").on("click", function () {
var div = $("#AddedItems");

var uid = $("#getUser").attr("data-logName");
var TUid = $("#uid").attr("data-tID");
var TId = $('#TiD').attr("data-tID");
var ids = $("#AddedItems li").map(function () { return this.id }).get();

var trade = {
    FromUserID: uid,
    TID: TUid,
    itemTForId: TItemId,
    items: ids
}
$.ajax({
    type: "POST",
    url: "/Transaction/Create",
    data: trade

   });
});

控制器:我想如果我通过Transaction就可以了

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Transactions transaction)
    {
        if (ModelState.IsValid)
        {
            db.Transactions.Add(transaction);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(transactions);//not really concerned with where it goes right now
    }                             //just want to get the values in the db

交易模式

       public class Transactions
{


    // all the properties
    //
    //
    public ICollection<Item> items { get; set; }//this is not being stored

}

1 个答案:

答案 0 :(得分:1)

由于您使用的是ValidateAntiForgeryToken属性,因此您的ajax请求 必须 包含由@Html.AntiForgeryToken()生成的令牌。例如:这是您的表单:

<form>
@Html.AntiForgeryToken()

//other field
</form>

@ Html.AntiForgeryToken()默认情况下将使用name="__RequestVerificationToken"呈现隐藏字段。您可以按如下方式尝试ajax:

var trade = {
    FromUserID: uid,
    ToUserID: TUid,
    itemTradedForId: TItemId,
    items: ids,
    __RequestVerificationToken: $("[name='__RequestVerificationToken']").val()
}

$.ajax({
    type: "POST",
    url: "/Transaction/Create",
    contentType: 'application/json; charset=utf-8',                     
    data: JSON.stringify(trade)
   });
});

同时指定contentType: 'application/json; charset=utf-8'JSON.stringify(trade)