简体   繁体   English

使用模型将函数从cshtml调用到cshtml.cs

[英]Call function from cshtml to cshtml.cs using Models

I am new to asp.net core and Razor, i am trying to call a function from cshtml page to his inner cs page: 我是asp.net core和Razor的新手,我试图从cshtml页调用一个函数到其内部cs页:

<button onclick="@{Model.GetUserInfo(1);};" type="submit">Search</button>

cshtsml.cs cshtsml.cs

public UserInfo GetUserInfo(int userId)
{
    using (var client = new HttpClient())
    {
        var response = client.GetAsync($"localhost:44322/api/User/user/{userId}{userId}");
        var body = response.Result.Content.ReadAsAsync<UserInfo>().Result;

        return body;
    }
}

I would like to get the information back from the api and display the information that i received. 我想从api取回信息并显示我收到的信息。

With this code if i put { } around the Model.GetUserInfo(1); 如果使用此代码,则将{}放在Model.GetUserInfo(1)周围; it doesn't display the button, without the { } it just doesn't compile. 它不显示按钮,没有{}就不会编译。

Any of you can help me with it? 你们有谁能帮我吗? thanks. 谢谢。

Step 1 - You can write a javascript function which will send an ajax request to your controller method 第1步-您可以编写一个JavaScript函数,该函数会将ajax请求发送到您的控制器方法

Step 2 - Return the data you want from this method 第2步-从此方法返回所需的数据

Assuming your controller name is Home, you can do something like this- 假设您的控制器名称为Home,则可以执行以下操作-

<button onclick="GetData()" type="submit">Search</button>

function GetData() {
    $.get("/Home/GetUserInfo", function (data) {
        // Here put what do you want from received data
    });
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM