Reputation: 452
I need to mix and match JavaScript and C# using Razor syntax in the same statement. I could be using @: wrong for writing JavaScript inside of Razor code because the last expression in the Razor code block breaks all the JavaScript after the block.
var myVar = document.getElementById("myId");
var linkText = "someText";
var JSVar = X; //X represents some number
@{
int ID = JSVar;
@:myVar.innerHTML = @Html.ActionLink(@:linkText, "Details", "Cards", new { Id = ID});
}
I've also tried to accomplish this as a single expression without the code block, like this:
myVar.innerHTML = @Html.ActionLink(@:linkText, "Details", "Cards", new { Id = @:IdVar });
This breaks the following JavaScript as well.
Upvotes: 2
Views: 1610
Reputation: 62260
Based on the question, it seems that you want to contract a link dynamically at client-side with value from JSVar.
If so, you could just append JSVar to URL. For example,
<input id="txtValue" type="text" value="Stackoverflow" />
<a id="myId">Navigate to Page</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#myId").click(function () {
var JSVar = $("#txtValue").val();
location.href = "@Url.Action("About", "Home")/id=" + JSVar;
});
})
</script>
Upvotes: 1
Reputation: 1700
I don't think this is possible to do. What I do (when I can't come up with a better alternative) is to store razor variables (like an href or model value) in a hidden field or div which I can then pull out via javascript.
What are you trying to accomplish exactly? There may be a more elegant way to achieve it?
Upvotes: 0