Jesper Petersen
Jesper Petersen

Reputation: 39

How to bind HtmlString?

Text that I must have displayed is displayed fine in my textbox and showcased as I would want it. But the problem is when I need to update the text so it tells me that there is nothing so it tells me it has a null value.

It exists in the database with text.

index.cshtml

@model MVCOrdklar2015.Models.Admin.IndholdViewModel
@using (Html.BeginForm("index", "AdminIndhold", FormMethod.Post))
        {
            <fieldset>
                <div class="form-group">
                    <div class="col-xs-12">
                        @Html.TextAreaFor(i => i.IndholdText, new
                   {
                       @class = "ckeditor"
                   })
                    </div>
                </div>
            </fieldset>
            <div class="form-group form-actions">
                <div class="col-xs-12">
                    <button type="submit" class="btn btn-effect-ripple btn-primary">Opdater</button>
                </div>
            </div>
        }

Model:

namespace MVCOrdklar2015.Models.Admin
{
    public class IndholdViewModel
    {
        public HtmlString IndholdText
        {
            get; set;
        }
    }
}

Controller:

[HttpPost]
    [ValidateInput(false)]
    public ActionResult Index(IndholdViewModel ModelInput)
    {
        if (!ModelState.IsValid)
        {
            DataLinqDB db = new DataLinqDB();
            var forsideindhold = db.forsides.FirstOrDefault(i => i.Id == 1);
            if (forsideindhold != null)
            {
                //error here
                forsideindhold.tekst = new HtmlString(ModelInput.IndholdText.ToString()).ToString();

                db.SubmitChanges();

                return RedirectToAction("index/Opdater");
            }
        }
        return View();
    }

You can see the picture here, see what it tells me the error. enter image description here

Upvotes: 1

Views: 195

Answers (1)

haim770
haim770

Reputation: 49095

The default model-binder would not bind a HtmlString property without registering a custom model-binder for it.

Try to use string combined with [AllowHtml] attribute instead:

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

And in your controller:

forsideindhold.tekst = ModelInput.IndholdText;

See MSDN

Upvotes: 2

Related Questions