简体   繁体   English

ASP.Net剃刀页面-如何将JSON从剃刀页面返回到javascript $ .getJson?

[英]ASP.Net Razor Pages - How do you return json from a razor page to javascript $.getJson?

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. 我对Web开发非常陌生,现在已经搜索了一段时间,但似乎找不到解决方案。 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. 我正在asp.net core 2.0中使用剃须刀页面,我想根据另一个下拉框的选择填充一个下拉框。 I set up the below javascript to hit a procedure in my razor page when the value of the first drop down box changes. 当第一个下拉框的值发生更改时,我将以下javascript设置为在剃刀页面中命中一个过程。 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. 我认为这是由于我的返回值引起的,但我似乎无法将其作为json值,因为当我尝试这样做时,它总是向我抛出错误。 The error is that "JSON is not valid in this context". 错误是“ JSON在此上下文中无效”。 Can anyone suggest to me how to return JSON from razor pages to a javascript call? 谁能给我建议如何将razor页面中的JSON返回到javascript调用?

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): 这是我的C#代码(我尝试使用JsonResult,但也不起作用):

           // 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. 所以我更改了代码,如下所示,现在我得到一个解析错误“ JSON.parse:JSON数据的第1行第1列的意外字符”,我无法弄清楚发生了什么,因为我看不到发生了什么数据又回来了,它无法解析。 Is my code below not converting to JSON and if not, what am I missing? 我下面的代码不会转换为JSON吗?如果不转换,我会丢失什么?

    @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: 这是我更新的过程的C#代码:

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

Rename your method to OnGet CardsByDivisionAndStatus (note "OnGet" prefix) and in jquery code change the url to 将您的方法重命名为OnGet CardsByDivisionAndStatus(请注意“ OnGet”前缀),然后在jquery代码中将URL更改为

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

Notice the handler querystring parameter name will be your method name without OnGet prefix. 注意,处理程序querystring参数名称将是您的方法名称,不带OnGet前缀。

So I figured out what the problem was. 所以我找出了问题所在。 Apparently I did not need to have the @URL.Action in my code. 显然,我的代码中不需要@ URL.Action。 It was causing me to not hit my C# code which in return caused a null response back to my call. 这导致我没有点击我的C#代码,这反过来导致了对我的电话的空响应。 I have modified my javascript code to be as below to show what I am talking about. 我已将我的JavaScript代码修改如下,以显示我在说什么。 Thanks Mohsin for trying to help me out. 感谢Mohsin尝试帮助我。

@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> }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ASP.NET Razor页面项目中使用Sencha ExtWebComponents? - How do you use Sencha ExtWebComponents in an ASP.NET Razor page project? 仅刷新 ASP.NET CORE Razor 页面中的内容页面 - Refresh only content page in ASP.NET CORE Razor Pages ASP.NET MVC 3 Razor页面中的JavaScript - JavaScript inside of ASP.NET MVC 3 Razor pages ASP.NET Razor Pages JavaScript文件返回未定义的错误 - ASP.NET Razor Pages JavaScript file returns undefined error 在ASP.NET MVC中,如何将ASP.NET剃须刀字符串传递到javascript onclick函数中? - In ASP.NET MVC how do I pass in ASP.NET razor strings into a javascript onclick function? 使用 JavaScript 如何将 JSON 从 Razor 页面发送到 MVC .NET Core 中的控制器 - Using JavaScript how do I sent JSON from Razor page to Controller in MVC .NET Core 从 JavaScript 传值到 C# ASP.NET 核心 Razor SQL 查询的页面 - Passing values from JavaScript to C# ASP.NET Core Razor Pages for SQL Querying 如何在 CKEditor 5 中使用 asp.net core razor Pages 上传图片 - How upload image in CKEditor 5 With asp.net core razor Pages 如何提交 asp.net 核心 razor 页面表单而不重新加载页面 - How to submit asp.net core razor pages form without reloading page 如何在尝试使用 Razor Pages 删除 ASP.NET Core 中的记录时显示确认消息 - How do I display a confirmation message with trying to delete a record in ASP.NET Core using Razor Pages
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM