【问题标题】:JS+ASP Net Core Get data from controllerJS+ASP Net Core 从控制器获取数据
【发布时间】:2021-11-11 13:19:04
【问题描述】:

问题出现了:如何使用js从asp net core中的控制器获取数据? 我试图正面发送一个帖子请求,但在我看来有一个更优雅的解决方案 同时,我需要在 Select 元素的 html 更改时发生这种情况 I wrote a script that changes the field when the select changes

    function Change_Aud() {
    var x = document.getElementById("Levelid").value;
    document.getElementById("Hardware_La").value = x ;
   
}

控制器示例

        public async Task<IActionResult> Get_Hardware_Unit(int id)
    {
        Level level  = _context.Levels.Where(p => p.Number == id.ToString()).First();
        
        return Content(level.Public_Hardware.ToString());
    }

【问题讨论】:

    标签: javascript asp.net-core


    【解决方案1】:

    在cshtml中测试页面代码:

    @{
        ViewData["Title"] = "Home Page";
        int count = 5;
    }
    <script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
    
    <script>
        function myFunction(selectObject) {
            var value = selectObject.value;
            $("#selectnum").html(value);
            backendfunc(value);
        }
        function backendfunc(value) {
            $.ajax({
                url: "/Test/Get_Hardware_Unit",
                type: "GET",
                data: { id: value },
                success: function (res) {
                    $("#convertnum").html(res);
                },
                error: function (hata, ajaxoptions, throwerror) {
                    $("#convertnum").html("convert failed");
                }
            });
        }
    </script>
    
    <div>
        <select name="num" id="num-select" onchange="myFunction(this)">
            <option value="">--Please choose an option--</option>
            <option value="1">One</option>
            <option value="2">Two</option>
            <option value="3">Three</option>
        </select>
    </div>
    <br />
    <br />
    <div>
        You select value is : <span id="selectnum"></span>
    </div>
    <br />
    <br />
    <div>
        After backend converted, here is : <span id="convertnum"></span>
    </div>
    

    我在 Controller 中的功能:

    public async Task<IActionResult> Get_Hardware_Unit(int id) {
        string result = string.Empty;
        if (id == 1) {
            result = "①";
        }
        if (id == 2)
        {
            result = "②";
        }
        if (id == 3)
        {
            result = "③";
        }
        return Content(result);            
    }
    

    测试结果

    【讨论】:

      猜你喜欢
      • 2018-01-18
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 2022-07-27
      • 1970-01-01
      • 2021-07-16
      • 2018-04-18
      • 1970-01-01
      相关资源
      最近更新 更多