Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use C# variable inside of javascript block variable using Razor?

I have a view file(.cshtml) with this C# block in top of file:

@{
List<string> selectedCategories = new List<string>();

}

well I want to use the selectedCategories list in the following javascript block

@section scripts{
<script src="../../Scripts/jquery-1.6.4-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#list-all-categories").selectable({
            stop: function () {
                var result = $("#selectedCategories").empty();
                @selectedCategories.Clear()
                $(".ui-selected", this).each(function () {
                    var Mytext = $(this).text();

                    @selectedCategories.Add(Mytext.toString());

                });

            }
        });
    });
</script>

}

SO, it's does not work!... at all!!!

I have some errors like this: -Conditional compilation is turned off -The name 'Mytext' does not exist in the current context -...

what should I do?! help me please!

like image 997
amir-yeketaz Avatar asked Aug 08 '26 18:08

amir-yeketaz


2 Answers

  • Javascript is run in the browser.
  • Razor code is run in the webserver

You can't mix them like that.

You need to create form elements by using jQuery only and then post them back to the sevrer.

<script type="text/javascript">
    $(document).ready(function () {
        $("#list-all-categories").selectable({
            stop: function () {
                $(".selectedItems").remove();
                $(".ui-selected", this).each(function () {
                var Mytext = $(this).text();
                $('#myform').append('<input type="hidden" name="selectedCategory" value="' + MyText + '" class="selectedItems" />');
            });
        });
    });
</script>

change "myform" to the form that is posted.

And then you get the items as:

public ActionResult YourAction(string[] selectedCategory)
{
}
like image 179
jgauffin Avatar answered Aug 11 '26 12:08

jgauffin


The problem is that razor expressions are compiled server-side, before the web page reaches web browser. But the JavaScript is interpreted at "run time", at client-side. Therefore you cannot add stuff to a c#-list from JavaScript like that.

Perhaps, if you need to maintain a c#-list in the backend, you could make an action on the controller that you can send items to via Ajax.

like image 23
Christoffer Avatar answered Aug 11 '26 14:08

Christoffer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!