Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - ASP MVC Razor encode special characters in input placeholder

This is my code:

Model:

[Required]
[DataType(DataType.Text)]
[Display(Name = "Your company's name")]
public string CompanyName { get; set; }

View:

@Html.TextBoxFor(m => m.CompanyName, new { @class = "account-input", @placeholder = @Html.DisplayNameFor(m => m.CompanyName), @id = "companyname" })

It will be rendered like this:

Your company's name

html output:

<input class="account-input" data-val="true" data-val-required="The Your company's name field is required." id="companyname" name="CompanyName" placeholder="Your company&amp;#39;s name" type="text" value="">

It should be look like this:

Your company's name

Why is the text does not render correctly and how can I prevent this?

I already tried this:

@Html.TextBoxFor(m => m.CompanyName, new { @class = "account-input", @placeholder = @Html.Raw(@Html.DisplayNameFor(m => m.CompanyName)), @id = "companyname" })

and this

@Html.TextBoxFor(m => m.CompanyName, new { @class = "account-input", @placeholder = @Html.Encode(@Html.DisplayNameFor(m => m.CompanyName)), @id = "companyname" })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think this post will help you:

HTML encode decode c# MVC4

I think there are other ways to get this behaviour, but this is one option of using the TextBox:

@Html.TextBox("CompanyName", HttpUtility.HtmlEncode("Your company&#39;s name"))

There is also HttpUtility.HtmlDecode, which might help with our save action.

update

if you wrap HttpUtility.HtmlDecode around your place holder:

@Html.TextBoxFor(m => m.CompanyName, new { @class = "account-input", 
@placeholder = HttpUtility.HtmlDecode(Html.DisplayNameFor(x => x.CompanyName).ToHtmlString()), 
@id = "companyname" })

the placeholder returns as: placeholder="Your company's name"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...