简体   繁体   中英

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 . 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.

$( "#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

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".

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.

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

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 :

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



    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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