我的jquery ajax在asp.net mvc中不起作用

时间:2016-09-12 21:15:10

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

我希望通过Jquery Ajax在Asp.Net MVC中发送数据

但是当函数创建被调用时错误部分被执行

这里是我的Java脚本

    function create() {
        $.ajax({
            url: "@Url.Action(actionName:"Create",controllerName:"Tag",routeValues:new { Area="Admin"})",
            contentType: "application/json",
            type: "POST",
            dataType: "json",
            data: $("#myForm").serialize(),
            success: function (response) {
                eval(response.Script);
            }, error: function () {
                alert("Error");
            }
        });

这是我的行动方法

    [ValidateAntiForgeryToken,HttpPost, AjaxOnly]
    public ActionResult Create(Tag tag)
    {            
        JsonData data = new JsonData();
        if (ModelState.IsValid)
        {
            if (TagOperation.Where(x => x.Text == tag.Text) != null)
            {
                try
                {
                    TagOperation.Add(tag);
                    data.Script = MessageBox.Show("Message", MessageType.Success).Script;
                    return RedirectToAction(actionName: "Index", controllerName: "Tag", routeValues: new { Area = "Admin" });
                }
                catch (Exception ex)
                {
                    data.Script = MessageBox.Show("Message", MessageType.Error).Script;
                    return Json(data);
                }
            }
        }
        data.Script = MessageBox.Show(ModelState.GetErrors(), MessageType.Warning).Script;
        return Json(data);
    }

这是我通过Jquery Ajax发送数据的视图

@using (Html.BeginForm("Create", "Tag", FormMethod.Post, new { id = "myForm" })){
    @Html.AntiForgeryToken()
<div class="form-horizontal">        
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Text, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Text, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input onclick="create();" type="button" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>
}

2 个答案:

答案 0 :(得分:0)

尝试将[HttpPost]属性添加到您的操作结果方法中(默认情况下,操作结果使用GET)

[HttpPost]  
public ActionResult Create(Tag tag){..}

答案 1 :(得分:0)

您可以尝试将令牌添加到请求标头。

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

var headers = {};

headers['__RequestVerificationToken'] = token;

$.ajax({
        headers: headers,
});