2

I am learning web development. And I just want to make a simple AJAX GET call in ASP.Net MVC Application and I want visualize how it works. But I am not able to do so. I am a beginner and I could have done any silly mistakes. But as of now there are no errors in my code.

Below is what I have:

So, I have a Index.cshtml file which is already loaded. Now in that page I want to make an Ajax GET call to one of the function that I have written in the HomeController and action name is Test. I just want to hit the breakpoint in that Test Action of Homecontroller and return something back to the Success of AJAX Call. In HomeController I have below Action

[HttpGet]
public ActionResult Test()
{
    return View("hello");
}

jQuery

    $.ajax({
        url: '/Home/Test',
        type: 'GET',
        success: function (html) {
            alert(html);
        },
        error: function (error) {
            $(that).remove();
            DisplayError(error.statusText);
        }
    });
}

Confusion: Do I need to create a cshtml for Test. But I actually do not want that. I just want the Test Action to return me one data. And I will display that data in my Already opened Index.csthml file.

Error: No error but I am not able to hit the breakpoint in Test Action of controller. Kindly note that Success of AJAX is hitting but I do not see any data. But I am sure it did not hit the test Action breakpoint.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Unbreakable
  • 7,776
  • 24
  • 90
  • 171
  • when are you calling your ajax code ? Any event triggers that code ? other wise your code is fine. – Anadi Jan 05 '17 at 18:57
  • GET requests may be cached by the browser. If you had called it once it may not reach your controller again. Watch the browser's network monitor to verify the request is made. – Jasen Jan 05 '17 at 19:00
  • There was a big answer down here for my question but now that answer is gone. :( – Unbreakable Jan 05 '17 at 19:01
  • yes I need that ajax call to get triggered on a function call. And that function call is working fine. This ajax request is getting hit. – Unbreakable Jan 05 '17 at 19:02
  • What kind of response do you want returned? A HTML fragment or JSON? – Jasen Jan 05 '17 at 19:02
  • just anything. I just want to get something back. – Unbreakable Jan 05 '17 at 19:02
  • Here's an [answer](http://stackoverflow.com/questions/19392212/how-to-use-jquery-or-ajax-to-update-razor-partial-view-in-c-asp-net-for-a-mvc-p/19410973#19410973) for a HTML fragment returned with a PartialView. – Jasen Jan 05 '17 at 19:03
  • As of now. I always get the success call back but I get the content of success is another function which in in the controller Home and action named "INDEX". Why the Index action is getting hit?? – Unbreakable Jan 05 '17 at 19:03
  • I don't want a partial view. I want to return just a content. please guide me. – Unbreakable Jan 05 '17 at 19:07
  • Then there's a good [answer here](http://stackoverflow.com/a/17734878/2030565). – Jasen Jan 05 '17 at 19:14

4 Answers4

4

Change your action method like this

[HttpGet]
public JsonResult Test()
{
    return Json("myContent",JsonRequestBehavior.AllowGet);
}

And in your success method in 'html' variable you will get back "myContent".

Anadi
  • 744
  • 9
  • 24
3

Example :

 function RemoveItem(ItemId) {

                if (ItemId && ItemId > 0) {
                    $.ajax({
                        cache: false,
                        url: '@Url.Action("RemoveItem", "Items")',
                        type: 'POST',
                        data: { id: ItemId },
                        success: function (result) {
                            if (result.success == true) {
                                $("#CartItemGridDiv").load('@Url.Content("~/User/Items/CartItemGrid")');
                                alert('Item Removed successfully.');
                            }
                            else {
                                alert('Item not removed.');
                            }
                        },
                        error: function (result) {
                            alert('Item not removed.');
                        }
                    });
                }
            }

        public ActionResult RemoveItem(int id)
        {
            if (id > 0)
            {
                bool addToChart = false;

                addToChart = Utilities.UtilityClass.RemoveItem(id);

                if (addToChart)
                {
                    return Json(new { success = true }, JsonRequestBehavior.AllowGet);
                }
            }
            return Json(new { success = false }, JsonRequestBehavior.AllowGet);
        }
            public ActionResult CartItemGrid()
        {
            List<CartItems> oItemList = (List<CartItems>)Session[MvcMAB.StringConst.CartItemSession];
            return View(oItemList);
        }
0

Since you don't want to return a view, you might need to return Json() instead of View() You need to Allow Get in the action. Like that:

    public ActionResult SomeGetAction(int? id)
    {
       //Some DB query here
       var myJsonList = myListQuery;
       return Json(myJsonList, JsonRequestBehavior.AllowGet);
    }

Or in case of just Simple string response:

 public ActionResult SomeGetAction()
    {

       return Json("My String", JsonRequestBehavior.AllowGet);
    }

I would recommend renaming html into response. Also change that to this in Error Response section.

 $.ajax({
    url: '/Home/Test',
    type: 'GET',
    success: function (response) {
        alert(response);
    },
    error: function (error) {
        $(this).remove();
        DisplayError(error.statusText);
    }
});

Enjoy.

Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45
0

C#:

public JsonResult Test()
    {
        return Json("hello");
    }

Jquery:

    $.ajax({
        url: '/Home/Test',
        type: 'Post',
        dataType: 'json',
        success: function (html) {
            alert(html);
        },
        error: function (error) {
            alert(error);
                       }
    });
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320