Replacing quotes in a html input

孤街浪徒 提交于 2021-02-10 16:50:35

问题


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("&#34;","&#quot;")
} " />

回答1:


use double quotes instead of single quotes ("") as shown below:

<input id="ModelDescription" type="hidden" value="Sam's little brother said &#34;I don't like apples&#34;." />



回答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 &quot;I don't like apples&quot;.">

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!