问题
I've got some strings coming through a Model and am making html inputs from them. More or less as below:
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
@{
this.Layout = "Views/Shared/Bootstrap.cshtml";
}
<input id="ModelDescription" type="hidden" value='@if(this.Model.Model.Description != null)
{
@this.Model.Model.Description.Replace('a','b')
} ' />
Which is all well and good. I've managed to get the replace a with b in there (the code I've inherited isn't the most stable of things) and that works, just as an example.
As you may well have gathered, we're having issues with quotes. Some users will have entered things like:
Sam's little brother said "I don't like apples".
Which of course means that our input becomes:
<input id="ModelDescription" type="hidden" value='Sam's little brother said "I don't like apples".' />
Meaning that the only thing that gets rendered is
Sam
Edit - Vikas' answer gave me...
<input id="ModelDescription" type="hidden" value="@if(this.Model.Model.Description != null)
{
@this.Model.Model.Description.Replace(""","&#quot;")
} " />
回答1:
use double quotes instead of single quotes ("") as shown below:
<input id="ModelDescription" type="hidden" value="Sam's little brother said "I don't like apples"." />
回答2:
You can use @Html.Raw
and ternary operator to show single quotes and double quotes like this:
<input id="ModelDescription" type="hidden"
value="@Html.Raw(this.Model.Model.Description != null ?
@this.Model.Model.Description.Replace('a','b') : "")" />
The above code will generate HTML markup like example below:
<input id="ModelDescription" type="hidden" value="Sam's little brother said "I don't like apples".">
Note: Better to use @Html.HiddenFor()
instead manually setting value
attribute like that.
Demo: .NET Fiddle
来源:https://stackoverflow.com/questions/52713520/replacing-quotes-in-a-html-input