tobynew
tobynew

Reputation: 347

C# MVC4 Save HTML in Textarea - Validation failing

I have a page creation form, using a Page class

Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Globalization;
using SpringHealthOne.SpringWS;
using System.Configuration;
using System.ComponentModel.DataAnnotations.Schema;

namespace SpringHealthOne.Models
{
    public class Page 
    {
        public int PageID { get; set; }
        [Required]
        public string Title { get; set; }

        [NotMapped]
        public MvcHtmlString PageBody { get; set; }

        public string Body
        {
            get { return PageBody.ToHtmlString(); }
            set { PageBody = new MvcHtmlString(value); }
        }

        public string MetaTitle { get; set; }
        public string MetaDescription { get; set; }
        public string Keywords { get; set; }
        public bool Published { get; set; }
    }
}

The form itself is simple enough, it includes a textarea with Ckeditor added to it. When trying to save the field initially i was getting unsafe input errors (the HTML), so i added [ValidateInput(false)] to the method:

[ValidateInput(false)]
[HttpPost]
public ActionResult Edit(Page page)
    {
        if (ModelState.IsValid)
        {
            db.Entry(page).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(page);
    }

I no longer get an exception, but the ModelState.IsValid is always set to false, and i get the error of:

The value '<HTML STRING>' is invalid.

Can anyone point me in the right direction? Im very new to C# and more so MVC4

Upvotes: 1

Views: 3599

Answers (1)

Henk Mollema
Henk Mollema

Reputation: 46581

I think AllowHtmlAttribute is what you're looking for. You can use it like this:

[AllowHtml]
public string Body { get; set; }

This allows you to use HTML markup in the string since it skips model validation for this property. You should not need the ValidateInput attribute. I don't think it's good to use it anyway, since it skips validation for the whole model, this might also cause the ModelState.IsValid property to be false since you skipped the validation. Also see this article.

Upvotes: 1

Related Questions