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.

10
  • when are you calling your ajax code ? Any event triggers that code ? other wise your code is fine. Commented Jan 5, 2017 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. Commented Jan 5, 2017 at 19:00
  • There was a big answer down here for my question but now that answer is gone. :( Commented Jan 5, 2017 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. Commented Jan 5, 2017 at 19:02
  • What kind of response do you want returned? A HTML fragment or JSON? Commented Jan 5, 2017 at 19:02

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

but id is going as url paramter visible in url , if i dont want that then?
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.

6 Comments

I do not understand your answer. I just want to return one string. may be "hello world".
What is this int? id and myListQuery and all.
@Unbreakable then return Json("Hello WOrld", JsonRequestBehavior.AllowGet);
@Unbreakable check my answer, I Edited it.
What about the ajax call. Do I need to change something in ajax call too. Can you see my ajax code..
|
-1

C#:

public JsonResult Test()
    {
        return Json("hello", JsonRequestBehavior.AllowGet);
    }

Jquery:

    $.ajax({
        url: '/Home/Test',
        type: 'Get',
        dataType: 'json',
        success: function (html) {
            alert(html);
        },
        error: function (error) {
            alert(error);
                       }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.