0

I was wondering how I could pass a string that I made with javascript into a code block in razor. Given the few lines of simple js below:

var k=0;
var str1 = 'Model.FeaturedItems[';
var str2 = '].SubHeadline.ToString();';
var query = str1 + k +str2;

How would I then pass the string query into a code block? something like this:

                   alert("@"+query);

should print the result of that line of code. EDIT: Basically I want to execute this code: Model.FeaturedItems[0].SubHeadline.ToString(); and do something with the result in jquery. However I keep getting a syntax error trying the above.

3
  • What is your syntax error? What are you trying to do here? Commented Sep 23, 2012 at 8:47
  • 1
    It is not clear what do you want to achieve... The code in your razor view is executed on the server side when your page is rendered. But your javascript is executed on client side in your browser. So you cannot pass values from javascript to code in razor because they are execute in different times in different places. Commented Sep 23, 2012 at 8:47
  • The error is: """ is not valid at the start of a code block. Only identifiers, keywords, comments, "(" and "{" are valid. Commented Sep 23, 2012 at 9:11

2 Answers 2

2

javascript works on client and razor on server, you trying execute client code on server. Just use c# in code blocks:

C# code:

@{
    int k = 0; 
    var query = Model.FeaturedItems[k].SubHeadline.ToString(); 
}

On client @query will contain some data, if it is in razor view:

<script type="text/javascript">
    alert(@query); 
<script>
Sign up to request clarification or add additional context in comments.

Comments

1

It's not possible. Main reason is that the JavaScript code runs on client-side and razor views are being rendered on server side. Create SubHeadlines array on client side ASP.NET MVC 3 Razor : Initialize a JavaScript array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.