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!
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)
{
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With