leora
leora

Reputation: 196499

how to save html to a database field

i have an tiny editor web page where my users can use this editor and i am saving the html into my database.

i am having issues saving this html to my database. for example if there is a name with a "'" or if there are other html character "<,",">" etc, my code seems to blow up on the insert.

Is there any best practices about taking any arbitrary html and have it persist fully to a db field without worrying about any specific characters.

Upvotes: 2

Views: 6295

Answers (4)

Hal
Hal

Reputation: 1264

Just reading through this - is your problem actually on the insert statement or do you get a problem from the web server before it ever hits your controller? Noticing that you tagged the question with asp.net-mvc, you may need to make sure that you have decorated your controller method with the [ValidateInput(false)] attribute.

Upvotes: 0

Jeff S
Jeff S

Reputation: 7484

I'm wondering if you are building the full query. Instead use a parameterized query and that should eliminate your data problems.

string sqlIns = "INSERT INTO table (name, information, other) VALUES (@name, @information, @other)";

SqlCommand cmdIns = new SqlCommand(sqlIns, db.Connection);
cmdIns.Parameters.Add("@name", info);
cmdIns.Parameters.Add("@information", info1);
cmdIns.Parameters.Add("@other", info2);
cmdIns.ExecuteNonQuery();

Upvotes: 6

Russ Clarke
Russ Clarke

Reputation: 17909

You could just HtmlEncode the data. You'll have a HttpContext.Current.Server object, so in pseudo code you'd just do:

Database.Save(HttpContext.Current.Server.HtmlEncode(myHtml));

and to retrieve it:

myHtml = HttpContext.Current.Server.HtmlDecode(DataBase.Load());

Upvotes: 0

Andrey
Andrey

Reputation: 60065

do you insert using SqlParameter? If yes, you should not have problems, check that.

Upvotes: 2

Related Questions