简体   繁体   English

在C#块中使用JavaScript变量

[英]Using a javascript variable inside C# block

i am trying to get a variable by javascript and using it in my C# block but it looks like impossible. 我试图通过javascript获取一个变量,并在我的C#块中使用它,但这似乎是不可能的。

this is my HTML: 这是我的HTML:

<select class="form-control" id="Category">
    @foreach (var item in Model.Categori)
    {
        <option value="@item.CategoriId">@item.CategoriName</option>
    }
</select>
<div id="Container"></div>

and this is my javascript code: 这是我的JavaScript代码:

$('#Category').on('change', function (e) {
   $("#Container").append(`@foreach (var item in Model.YetkinlikKategorileri.Where(x => x.Id == $('#Category').val()))
   {
       <p>hello</p>
   }`);
});

well is it possible to do something like that ? 那么有可能做这样的事情吗? if not is there another way ? 如果没有,还有别的办法吗?

You need something like this: 您需要这样的东西:

<script> 
var data = [
        @foreach (var item in dataList)
        {
            @Html.Raw("'"+item+"',")
        }
    ];
    $('#Category').on('change', function (e) {
        var lst = data.find(/*Your condition*/);
        for (var i = 0; i < lst.length; i++) {
            $("#Content").append("<p>hello</p>" + data[i] + "<br/>");
        }
    };
</script>

dataList is the data which comes from server. dataList是来自服务器的数据。

But in this way, you should get all data from server and put it into javascript data array. 但是通过这种方式,您应该从服务器获取所有数据并将其放入javascript data数组。 Then you should make lst by finding in data array. 然后,您应该通过查找data数组来创建lst

But using ajax is better than this razor code. 但是使用ajax比这个剃刀代码更好。

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

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