5

I am very new to web development and I've been searching around for a while now and I can't seem to find a solution to this. I am using razor pages in asp.net core 2.0 and I want to fill a drop down box based on another drop down box's selection. I set up the below javascript to hit a procedure in my razor page when the value of the first drop down box changes. When I run the code though, I can't get it to work. I think it is due to my return value but I can't seem to get that to be a json value as it keeps throwing an error at me when I try to. The error is that "JSON is not valid in this context". Can anyone suggest to me how to return JSON from razor pages to a javascript call?

Any help would be appreciated!

    @section Scripts {
<script type="text/javascript">
    $('#Department').change(function () {
        var selectedDepartment = $("#Department").val();
        var cardSelect = $('#Card');
        cardSelect.empty();
        if (selectedDepartment != null && selectedDepartment != '') {
            $.getJSON('@Url.Action("GetCardsByDivisionAndStatus")', { divisionID: selectedDepartment }, function (cards) {
                if (cards != null && !jQuery.isEmptyObject(cards)) {
                    cardSelect.append($('<option/>', {
                        Card_ID: null,
                        Card_Number: ""

                    }))
                    $.each(cards, function (index, card) {
                        cardSelect.append($('<option/>', {
                            Card_ID: card.Card_ID,
                            Card_Number: card.Card_Number
                        }));

                    });

                };

            });                                
        }
    });
</script>

}

And here is my C# code (I tried used JsonResult but that's not working either):

           // If the user selects a division then make sure to get the cards for that division only
    [HttpGet]
    public ActionResult GetCardsByDivisionAndStatus(string divisionID)
    {
        int checkinStatus;
        int intdivisionID;

        if (divisionID != "0" && divisionID != null)
        {
            // Retrieve a status of checked in so that only cards with a checked in status can
            // be checked out.
            checkinStatus = linqQuery.GetCardStatusByStatusDesc("Checked In", _Context);

            intdivisionID = Convert.ToInt32(divisionID);

            // Retrieve list of cards that have the checkin status ID
            CardList = linqQuery.GetCardListByStatusIDandDeptID(checkinStatus, intdivisionID, _Context);

            // Create the drop down list to be used on the screen.
            carddropdown = new List<CardDropDown>();
            carddropdown = loaddropdowns.ReturnDropDownList(CardList);
            return new JsonResult(CardList);
        }

        return null;
    } 

EDIT----------------------------------------------------------------------

So I changed the code as below and now I'm getting a parse error "JSON.parse: unexpected character at line 1 column 1 of the JSON data" I can't figure out what is going on as I can't see what the data is coming back that it can't parse. Is my code below not converting to JSON and if not, what am I missing?

    @section Scripts {
<script type="text/javascript">
    $('#Department').change(function () {
        var selectedDepartment = $("#Department").val();                 
        var cardSelect = $('#Card');
        cardSelect.empty();
        if (selectedDepartment != null && selectedDepartment != '') {
            $.getJSON('@Url.Action("/CheckOutCard?handler=CardsByDivisionAndStatus")', { divisionID: selectedDepartment }, function (cards) {
                if (cards != null && !jQuery.isEmptyObject(cards)) {
                    cardSelect.append($('<option/>', {
                        Card_ID: null,
                        Card_Number: ""

                    }))
                    $.each(cards, function (index, card) {
                        cardSelect.append($('<option/>', {
                            Card_ID: card.Card_ID,
                            Card_Number: card.Card_Number
                        }));

                    });

                };

            });                                
        }
    });
</script>

And here is my C# code for the procedure that I updated:

            // If the user selects a division then make sure to get the cards for that division only
    [HttpGet]
    public JsonResult OnGetCardsByDivisionAndStatus(string divisionID)
    {
        int checkinStatus;
        int intdivisionID;

        if (divisionID != "0" && divisionID != null)
        {
            // Retrieve a status of checked in so that only cards with a checked in status can
            // be checked out.
            checkinStatus = linqQuery.GetCardStatusByStatusDesc("Checked In", _Context);

            intdivisionID = Convert.ToInt32(divisionID);

            // Retrieve list of cards that have the checkin status ID
            CardList = linqQuery.GetCardListByStatusIDandDeptID(checkinStatus, intdivisionID, _Context);

            // Create the drop down list to be used on the screen.
            carddropdown = new List<CardDropDown>();
            carddropdown = loaddropdowns.ReturnDropDownList(CardList);
            var converted = JsonConvert.SerializeObject(carddropdown);
            return new JsonResult(converted);
        }

        return null;
    }

2 Answers 2

3

Rename your method to OnGetCardsByDivisionAndStatus (note "OnGet" prefix) and in jquery code change the url to

$.getJSON('/{PageRoute}?handler=CardsByDivisionAndStatus'
e.g.
$.getJSON('/About?handler=CardsByDivisionAndStatus'

Notice the handler querystring parameter name will be your method name without OnGet prefix.

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

4 Comments

Hi Mohsin, can you explain a little bit more about the name change? I want to make sure I understand the significance of it.
I believe the handler methods defined in Razor pages codebehind have to follow a convention "On{HttpMethod}" e.g OnGet or OnPost. Check the blog post codingblast.com/asp-net-core-razor-pages-handlers
I appreciate that. You answer moved me forward a little but I'm still not sure how to return a JSON result from the C# side.
Not sure why you are serializing carddropdown and then passing it to jsonresult. JsonResult can input a List<T> and serialize it as json response e.g. Try: return new JsonResult(carddropdown);
1

So I figured out what the problem was. Apparently I did not need to have the @URL.Action in my code. It was causing me to not hit my C# code which in return caused a null response back to my call. I have modified my javascript code to be as below to show what I am talking about. Thanks Mohsin for trying to help me out.

@section Scripts {
<script type="text/javascript">
    $('#Department').change(function ()
    {
        var selectedDepartment = $("#Department").val();
        var cardSelect = $('#Card');
        cardSelect.empty();
        if (selectedDepartment != null && selectedDepartment != '')
        {
            $.getJSON("/CheckOutCard?handler=CardsByDivisionAndStatus", { divisionID: selectedDepartment }, function (cards)
            {                                         
              $.each(cards, function (index, card)
              {
                  cardSelect.append($('<option/>',
                     {
                        value: card.card_ID,
                        text: card.card_Number
                     }));                        

               });

            });                                
        }
    });           
</script> }

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.