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 compil开发者_高级运维ation is turned off -The name 'Mytext' does not exist in the current context -...
what should I do?! help me please!
- 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)
{
}
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.
The Razor code is run by the web server as it's building text, at which point the Javascript is just plain text.
Razor just makes this stuff easier to read, but really it's just combining server execution with blocks of string text.
Your example is actually doing this:
Response.Write(@"
<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();");
Response.Write( selectedCategories.Clear() );
Response.Write(@"$("".ui-selected"", this).each(function () {
var Mytext = $(this).text();");
Response.Write( selectedCategories.Add(Mytext.ToString()));
Response.Write(@"});
}
});
});
</script>");
So you get a compilation exception on Mytext
because it doesn't exist server side - all that Javascript is just text strings to the server side .Net code.
精彩评论