You must always validate on the server-side, in case client-side validation is bypassed (i.e. JavaScript is turned off). To validate server-side, try this:
protected void btnAddNews_Click(object sender, EventArgs e)
{
// Only save to the database and update UI if the page is valid
if (Page.IsValid)
{
using (dbnewsEntities db = new dbnewsEntities())
{
var addNews = new tblNews();
addNews.headline = txtHeadlineForm1.Text;
addNews.headline2 = txtHeadlineForm2.Text;
addNews.ingress = txtIngressForm.Text;
addNews.news = txtNewsForm.Text;
addNews.date = DateTime.Now.ToString();
db.tblNews.Add(addNews);
db.SaveChanges();
}
lblResult.Text = "Nyhet sparad!";
}
}
Another approach is to bail out of the method if you find that page validation has failed, like this:
protected void btnAddNews_Click(object sender, EventArgs e)
{
// If the page is invalid, then return from the method
if (!Page.IsValid)
{
return;
}
using (dbnewsEntities db = new dbnewsEntities())
{
var addNews = new tblNews();
addNews.headline = txtHeadlineForm1.Text;
addNews.headline2 = txtHeadlineForm2.Text;
addNews.ingress = txtIngressForm.Text;
addNews.news = txtNewsForm.Text;
addNews.date = DateTime.Now.ToString();
db.tblNews.Add(addNews);
db.SaveChanges();
}
lblResult.Text = "Nyhet sparad!";
}
I personally like the first approach of saving if things are valid, because the second approach requires the first thing done is checking for the page not being valid and bailing out (read: return). To each their own.