Escape html with mvc3 razor

2019-07-18 12:03发布

问题:

I'm trying to create a link that just triggers a javascript function with parameters set by my mvc model. I have something that looks like this

<a onclick="$('foo_@Model.bar').toggle()"></a>

However this literally makes the onclick element 'foo@Model.bar' instead of printing the contents of Model.bar. How do I escape the Html without altering it?

回答1:

Just add brackets, tested it and works fine:

<a onclick="$('foo_@(Model.bar)').toggle()"></a>


回答2:

Just add parenthesis:

<a onclick="$('foo_@(Model.bar)').toggle()"></a>


回答3:

<a onclick="$(@string.Format('foo_{0}',Model.bar)).toggle()"></a>