Click here to Skip to main content
15,897,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

In my MVC application i created the view Index.cshtml and there i declared the C# variable..

Eg: string selectedvalue="";

now how to use it in the javascript function code which i wrote with in this Index.cshtml, so that i can append some text to this string in javascript function?

C#
<index>
<div>

string selectedvalue="";

// Coding Part

</div>
<script type="text/javascript">

function onchangeFT(e)
 {
     '@selectedvalue'= e.value; //e.value come form combobox and it is should be assigned to "selectedvalue"
        alert('@selectedvalue');
 }

</script>



It is giving me error...

any idea to solve this issue?
Posted

You cannot just have a c# variable in the .cshtml file and get it using javascript. Using the c# variable you get in the model, create a hidden field. Then use jquery (or javascript) to update the value based on the choice made in the select list.

I have created a sample that demonstrates this. Note that this is just an implementation using html & jquery. You will have to use this as a base for the mvc 3 implementation. Mainly, this is just to help you get the idea and not the full implementation itself.

http://jsfiddle.net/62qqk/[^]

In case you have more questions post it here, one of us will help!

Hope this helps!
 
Share this answer
 
v2
Comments
Karthik. A 7-Jun-12 12:29pm    
I noticed that you said javascript, but I have used jquery in the sample implementation... if using javascript, you may have to do the same in body.onload using the javascript way of reading / setting values.
P_A_1 8-Jun-12 2:40am    
Hi how to make hide the variable in the form
Karthik. A 8-Jun-12 9:28am    
I am not sure I understand. Can you elaborate? Which variable are you referring to?
if razor
var value = @servervariable

else
var value = <%: servervariable %>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900