阿贾克斯没有击中控制器

时间:2017-05-29 16:46:40

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

这里我试图在点击id =" abc"的按钮时添加新评论。在单击按钮时,必须调用ajax,从中调用TaskAssignedDailyLogController的Create操作。换句话说,ajax没有点击TaskAssignedDailyLogsController的创建动作 现在,问题是ajax没有调用创建动作

下面是Ajax

<script>
    $(document).ready(function () {

    $(document).on('click', '#abc', function () {
        debugger          
        var you = $("#myForm1").serialize();       
        var parameter = { taskAssignedDailyLog: you };

        $.ajax({
            url: '@Url.Action("Create", "TaskAssignedDailyLogs")',
            type: "post",
            dataType: "html",
            data: parameter,
            success: function (data) {
                alert(data);
                $(".newCommentList").empty();

                $(".newCommentList").html(data);
            }
        });

    });
});
</script>


下面是Create.cshtml

@using (Html.BeginForm("Create", "TaskAssignedDailyLogs",   FormMethod.Post, new { @id = "myForm1" }))
{
    @Html.AntiForgeryToken()

<div class="form-horizontal empcreate">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    @Html.HiddenFor(x => x.TskAssId)

    <div class="form-group">
        @Html.LabelFor(model => model.Comments, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Comments, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Comments, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.WrkHrs, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.WrkHrs, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.WrkHrs, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PercentCompleted, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.PercentCompleted, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PercentCompleted, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <button type="button" value="Create" class="btn btn-default" id="abc"> Add</button>
        </div>
    </div>
</div>
}



以下是控制器

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(TaskAssignedDailyLog taskAssignedDailyLog)
    {
        if (ModelState.IsValid)
        {

            taskAssignedDailyLog.PostedBy = 1;
            taskAssignedDailyLog.PostedOn = DateTime.Now.Date;
            db.TaskAssignedDailyLogs.Add(taskAssignedDailyLog);
            db.SaveChanges();
            return RedirectToAction("Index", new { ProjectId =1 , TskAssId = taskAssignedDailyLog.TskAssId });
        }           
        return View(taskAssignedDailyLog);
    }

1 个答案:

答案 0 :(得分:0)

我在SO中看到过这个问题的一个可能的解决方案。我不记得是谁编写了这段代码,但它按预期工作:

/***********************************************
 * AuthorizeAttribute filter for JsonResult methods
 * 
 * Validates AntiForgeryToken from header of AJAX request.
 * AntiForgeryToken must be placed into that header.
 ************************************************/

/*
 View
    @Html.AntiForgeryToken()
    <script>
        var headers = {};
        headers["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        $.ajax({
            type: "POST", //Type must be POST
            url: url,
            dataType: "json",
            headers: headers,

 Controller
    [ValidateJsonAntiForgeryToken]
    public JsonResult Method() { }
*/

public sealed class ValidateJsonAntiForgeryToken : AuthorizeAttribute
{
    public JsonResult deniedResult = new JsonResult()
    {
        JsonRequestBehavior = JsonRequestBehavior.AllowGet,
        Data = new { StatusCode = HttpStatusCode.Forbidden, Error = "Access Denied" }
    };

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        System.Diagnostics.Debug.WriteLine("ValidateJsonAntiForgeryToken");
        var request = filterContext.HttpContext.Request;

        if (request.HttpMethod == WebRequestMethods.Http.Post && request.IsAjaxRequest() && request.Headers["__RequestVerificationToken"] != null)
        {
            AntiForgery.Validate(CookieValue(request), request.Headers["__RequestVerificationToken"]);
        }
        else
        {
            filterContext.Result = deniedResult;
        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        System.Diagnostics.Debug.WriteLine("ValidateJsonAntiForgeryToken HandleUnauthorizedRequest ");
        filterContext.Result = deniedResult;
    }

    private static string CookieValue(HttpRequestBase request)
    {
        var cookie = request.Cookies[AntiForgeryConfig.CookieName];
        return cookie != null ? cookie.Value : null;
    }
}

只需使用新属性修饰您的方法: [ValidateJsonAntiForgeryToken]

还有另一种解决方案,例如here

让我知道它是否适合你。