简体   繁体   中英

Return plain text JSON request

I am trying to call an ActionResult and update the value of an img on the page based on the returned result from the Action , but for some reason I post to a new page that just prints the string

   public ActionResult Favorite(int? id)
    {
        int PId = Convert.ToInt32(pid);
        if (MyDb.CheckExist(Convert.ToInt32(User.Identity.Name),PId))
        {
            var UF = MyDb.GetExist( Convert.ToInt32(User.Identity.Name),PId);
            MyDb.Delete(UF);
            MyDb.Save();
            return Json(new { Url= "/Content/oldimage.png" }, JsonRequestBehavior.AllowGet);
        }

        else
        {
            UFs UF = new UFs();
            UF.Id = PId;
            UF.UserId = Convert.ToInt32(User.Identity.Name);
            UF.CreatedDate = DateTime.Now;
            MyDb.Add(UF);
            MyDb.Save();
            return Json(new {  Url= "/Content/newimage.png"}, JsonRequestBehavior.AllowGet);//return favorite image
        }

    }

my anchor tag that calls my ajax

   <a href='<%= Url.Action("Favorite","Home", new { id = item.Id })%>' class="Image" style="text-decoration:none">
            <img src="/Content/Images/oldimage.png" alt="FavoriteImage" style="height:25px;width:30px"  id="favorite<%:item.Id %>" class="ImageTag" /></a>


  $('.Image').click(function () {

        var id = this.children('.ImageTag').attr('id');
        $.ajax({
            url: this.href,
            type: 'POST',
            dataType: "json",
            success: function (data) {
                 $('#' + id).attr('src', data.Url);

            },
            error: function (xhr, ajaxOptions, thrownError) {
                $.unblockUI();
            }
        });
        return false;
    });

and what happens is the action on the server is hit but the page posts to Home/Favorite displaying the returned Json. Home/Favorite is not even a view.

You should prevent the default behavior, the link is making a new request for the Favorite Action refreshing the whole page, getting as response the JSON.

$('.Image').click(function(event) {
  event.preventDefault();

  //do stuff here

});

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