I currently have a link in the below form:
<a href="javascript:changeNumbers('Numbers', '@Url.Action("ChangeNumbers")')">Change</a>
In order to fit the look of the site in which I'm adding this link, I want to change it to a button input, as so:
<input type="button" value="Change" onclick="changeNumbers('Numbers', '@Url.Action("ChangeNumbers")')" />
However, I'm running into a snag with this second form: the single quotes around @Url.Action("ChangeNumbers")
are being flagged as Unterminated string constant
. Can anyone tell me what I'm doing incorrectly and how to fix it?
EDIT
It didn't occur to me to just try the page - it looks like the second form works. So now my question is - why is Visual Studio flagging this as incorrect?
You're not doing anything "incorrectly" per se, it's just that Razor isn't perfect, and things like quotes within quotes tend to cause it to freak.
One quick fix would be to store the URL in a variable and then use the variable:
@{ var url = Url.Action("ChangeNumbers"); }
<input type="button" value="Change" onclick="changeNumbers('Numbers', '@url')" />
However, an even better fix is to not use the onclick
attribute at all. Put this where it belongs: in JS.
<script>
$('#myButton').on('click', function () {
changeNumbers('Numbers', '@Url.Action("ChangeNumbers")');
});
</script>
Used jQuery above, since it's included in MVC by default
I've found that to make Visual Studio happy in this scenario, the easiest thing to do is simply change the <input />
element to a <button></button>
element and the error will resolve itself:
<button type="button" onclick="changeNumbers('Numbers', '@Url.Action("ChangeNumbers")')">Change</button>
Otherwise, to continue using an <input />
the markup will need to be changed to the following:
<input type="button" value="Change" onclick="@("changeNumbers('Numbers', '" + Url.Action("ChangeNumbers") + "')")" />