İyad Mansür
İyad Mansür

Reputation: 60

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.

this is my 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:

$('#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 ?

Upvotes: 0

Views: 507

Answers (1)

Hossein Badrnezhad
Hossein Badrnezhad

Reputation: 502

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.

But in this way, you should get all data from server and put it into javascript data array. Then you should make lst by finding in data array.

But using ajax is better than this razor code.

Upvotes: 1

Related Questions