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

时间:2022-12-04 16:43:16

Here is the response from the api action . 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 . it will pass the action completely without any error but the ajax request just give me an exception and it doesnt successed.

下面是api操作的响应。我编写了一个web api操作,如下所示,当我通过ajax请求调用它时,它完全可以完成,但是它不会给出ajax成功的结果。它将完全传递操作,没有任何错误,但是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);

2 个解决方案

#1


2  

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方法exepcts“article”和“tags”,但您只提交“article”,而不告诉它该数据项实际上是表示“article”还是表示“tags”。

You're submitting tags on the querystring (url:"/api/ArticlesApi/?tags="+ $( "#articleTags" ).val(),) even though it's a POST method. the API method will almost certainly ignore this.

您正在向querystring提交标记(url:“/api/ArticlesApi/?”标签="+ $("#articleTags").val(),尽管它是一个POST方法。API方法几乎肯定会忽略这一点。

Move your tags data into the "data" object of the $.ajax call and you should have more luck.

将您的标记数据移动到$的“数据”对象中。ajax调用,您应该有更多的运气。

#2


1  

i find out what my problem :) !!! i used JavaScriptSerializer to test my api response to be sure that is in the correct Json format . 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 . 2. i sent something null . here is the correct code :

我发现了我的问题:)!!!我使用了JavaScriptSerializer测试我的api响应,以确保它是正确的Json格式。它给了我一个例外,我发现了我真正的问题。1。我在api操作中使用了include,最好不要使用。2。我发送了一些空的东西。下面是正确的代码:

[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);



    }

#1


2  

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方法exepcts“article”和“tags”,但您只提交“article”,而不告诉它该数据项实际上是表示“article”还是表示“tags”。

You're submitting tags on the querystring (url:"/api/ArticlesApi/?tags="+ $( "#articleTags" ).val(),) even though it's a POST method. the API method will almost certainly ignore this.

您正在向querystring提交标记(url:“/api/ArticlesApi/?”标签="+ $("#articleTags").val(),尽管它是一个POST方法。API方法几乎肯定会忽略这一点。

Move your tags data into the "data" object of the $.ajax call and you should have more luck.

将您的标记数据移动到$的“数据”对象中。ajax调用,您应该有更多的运气。

#2


1  

i find out what my problem :) !!! i used JavaScriptSerializer to test my api response to be sure that is in the correct Json format . 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 . 2. i sent something null . here is the correct code :

我发现了我的问题:)!!!我使用了JavaScriptSerializer测试我的api响应,以确保它是正确的Json格式。它给了我一个例外,我发现了我真正的问题。1。我在api操作中使用了include,最好不要使用。2。我发送了一些空的东西。下面是正确的代码:

[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);



    }