Apologies if I'm using the wrong terminology, I'm fairly new to this technology.
I have a view which we'll call MainView.cshtml:
<div>
@RenderPartial("_Partial");
</div>
<script type="text/javascript">
$(document).ready(function() {
someFunctionDefinedIn_Partial();
}
</script>
The _Partial view has javascript that defines a function (in this case someFunctionDefinedIn_Partial
.
function someFunctionDefinedIn_Partial()
{
// This uses the "@" syntax to access C# variables, which can be done in .cshtml
alert("Hello. This variable is from C#: @ClassInCSharp.Variable");
}
When I run the code above I'm told in the chrome console that the function someFunctionDefinedIn_Partial doesn't exist. I'm guessing this is because javascript in a partial doesn't make its way out to the container.
I looked around a bit and found that I can extract the javascript to its own .js file and reference that as shown in this SO post: How to render JavaScript into MasterLayout section from partial view?
However, the post above suggests extracting javascript into its own separate file .js. If I do this, then I am using "raw" javascript, so I can't use the @ notation to reference variables from my C#.
Is it possible to somehow include javascript in my MainView.cshtml which also has access to the @ syntax so I can use C# methods/variables? If not, is it possible to create an external javascript file, but have it be a .cshtml file so I can use the "@" syntax?