简体   繁体   English

在mvc中对api操作的ajax请求不执行成功事件(asp.net webapi)

[英]The ajax request to an api action in mvc doesn't execute the success event (asp.net webapi)

Here is the response from the api action . 这是api行动的回应。 I write a web api action as below it works completely done when i call that via ajax request but it wont give the result of success in ajax . 我写了一个web api动作如下所示,当我通过ajax请求调用它时它完全完成,但它不会在ajax中给出成功的结果。 it will pass the action completely without any error but the ajax request just give me an exception and it doesnt successed. 它将完全传递动作而没有任何错误,但是ajax请求只是给了我一个例外而且它没有成功。

$( "#btnSubmit" ).click( function ( e ) {
            e.preventDefault();
            var form = $( "#sendArticle" );
            if ( !form.valid() ) {
                return false;
            }
            var articles = {

                    "ArticleTitle": $( "#ArticleTitle" ).val(),
                    "CategoryId": $( "#CategoryId" ).val(),
                    "ArticleText": CKEDITOR.instances.ArticleText.getData(),
                    "ArticleImage": "/images/" + $( "div[class='file-caption-name']" ).attr( "title" )

            };


            $.ajax( {
                url:"/api/ArticlesApi/?tags="+ $( "#articleTags" ).val(),                   
                type:"post",
                contentType:"application/json;charset=utf-8",
                data:JSON.stringify( articles ),
                success: function (data) {

                            $("#grid").data("kendoGrid").dataSource.read();
                            $("#ArticleTitle" ).val( "" );
                            $( "#CategoryId" ).val( "" );
                            CKEDITOR.instances.ArticleText.setData( "" );
                            $.notify( "عملیات با موفقیت انجام شد", "success" );
                },
                error: function () {
                    $.notify( "خطایی رخ داده است", "error" );
                }
            } );
        } );

and here is the webapi action 这是webapi行动

public IHttpActionResult PostArticle(Article article, string tags)
    {


            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }



            article.UserId = "f9afb0fb-3479-4a4e-9460-ecbc642fe089";
            article.ArticleDate = DateTime.Now;
            article.ArticlePoint = 0;
            db.Articles.Add(article);
            db.SaveChanges();
            if (tags != null)
            {
                int[] arrayTag = tags.Split(',').Select(id => Convert.ToInt32(id)).ToArray();
                foreach (var item in arrayTag)
                {

                    Tag t = new Tag();
                t = db.Tags.Where(c => c.TagId == item).FirstOrDefault();

                article.Tags.Add(t);

                }
                db.Entry(article).State = EntityState.Modified;
                db.SaveChanges();
            }

        return CreatedAtRoute("DefaultApi", new { id = article.ArticleId }, article);

you're submitting the wrong data. 你提交错误的数据。 the API method exepcts "article" and "tags" but you're only submitting "article", and you're not telling it whether that data item is in fact meant to represent "article" or whether it's "tags". API方法会删除“文章”和“标签”,但您只是提交“文章”,而您并没有告诉它该数据项是否实际上意味着代表“文​​章”或它是否是“标签”。

You're submitting tags on the querystring ( url:"/api/ArticlesApi/?tags="+ $( "#articleTags" ).val(), ) even though it's a POST method. 你在查询字符串上提交标签( url:"/api/ArticlesApi/?tags="+ $( "#articleTags" ).val(), )即使它是一个POST方法。 the API method will almost certainly ignore this. API方法几乎肯定会忽略这一点。

Move your tags data into the "data" object of the $.ajax call and you should have more luck. 将您的标签数据移动到$ .ajax调用的“数据”对象中,您应该有更多的运气。

i find out what my problem :) !!! 我发现我的问题:) !!! i used JavaScriptSerializer to test my api response to be sure that is in the correct Json format . 我使用JavaScriptSerializer测试我的api响应,以确保它是正确的Json格式。 it provide me an exception and i found what is exactly my problem . 它提供了一个例外,我发现了什么是我的问题。 1. i used include in my api action, that is better not to use . 1.我在我的api动作中使用了include,最好不要使用。 2. i sent something null . 我送了一些东西。 here is the correct code : 这是正确的代码:

[ResponseType(typeof(Article))]
    public IHttpActionResult PostArticle(Article article, string tags)
    {


            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }




            article.UserId = "f9afb0fb-3479-4a4e-9460-ecbc642fe089";
            article.ArticleDate = DateTime.Now;
            article.ArticlePoint = 0;
            db.Articles.Add(article);
            db.SaveChanges();
            if (tags != null)
            {
                int[] arrayTag = tags.Split(',').Select(id => Convert.ToInt32(id)).ToArray();
                foreach (var item in arrayTag)
                {

                    Tag t = new Tag();
                t = db.Tags.Where(c => c.TagId == item).FirstOrDefault();

                article.Tags.Add(t);

                }
                db.Entry(article).State = EntityState.Modified;
                db.SaveChanges();
            }
        var category = db.ArticleCategories;
        var obj = new {article.ArticleDate,article.ArticleId,article.ArticleTitle,article.Category}; 
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(obj);

        return CreatedAtRoute("DefaultApi", new { id = article.ArticleId }, obj);



    }

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

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