Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an Editor Template for Boolean? (.EditorFor<>)

I'm trying to define a Boolean.cshtml to use with EditorFor using the following code:

@{
   var o = ViewData.ModelMetadata;
}

<div class="editor-for">
    @Html.CheckBox(o.PropertyName,
                   ViewData.Model,
                   new { @class="tickbox-single-line" })
</div>

Unfortunately, Model is null and I get the following non-descriptive error:

CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'CheckBox' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

After reading this I tried the following:

@Html.CheckBox(o.PropertyName,
               ViewData.Model ?? false,
               new { @class="tickbox-single-line" })

But I get exactly the same error. The View code is simply:

@Html.EditorFor(m => m.RememberMe)

What am I doing wrong in Boolean.cshtml?

like image 298
Luis Ferrao Avatar asked Dec 20 '22 14:12

Luis Ferrao


1 Answers

Not sure this is the best way, but I think you just have a problem with ViewData.Model, which is (if I'm not wrong), the dynamic problematic thing.

So... cast it !

@{
   var o = ViewData.ModelMetadata;
   bool model = (bool)ViewData.Model;
}

<div class="editor-for">
    @Html.CheckBox(o.PropertyName,
                   model,
                   new { @class="tickbox-single-line" })
</div>

but if I'm not wrong, an EditorTemplate would rather look like

@model bool

<div class="editor-for">
   @Html.CheckBox("", Model, new{@class="tickbox-single-line"})
<div>
like image 59
Raphaël Althaus Avatar answered Dec 23 '22 02:12

Raphaël Althaus