Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC 3 EditorTemplate for DateTime Fields Error

This code was converted from some ASP.Net MVC 2 code in this tutorial:
MVC 2 Editor Template with DateTime

It is a custom EditorTemplate for DateTime fields stored as 'EditorTemplates/DateTime.cshtml'.

@Model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" })

However I get the following error when using @Html.EditorFor(model => model.NewAbsence.StartDate):

CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'TextBox' 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.

I've seen some similar posts on here which mention casting the parameter of the EditorFor method, however I cannot seem to get this to work in my example.

Could someone please point out what I will need to change in my code. Thanks.

like image 803
Banford Avatar asked Feb 14 '11 13:02

Banford


2 Answers

Actually it's @model with lowercase m:

@model DateTime?
 ^

instead of:

@Model DateTime?
like image 105
Darin Dimitrov Avatar answered Oct 20 '22 20:10

Darin Dimitrov


So to sort of summarize what people are saying, and make it a bit more generic. If your view is declaring that it accepts dynamic models:

@model dynamic

Then things like extension methods will not be able to infer the types of arguments passed to them. Here are two examples (using Razor because it's awesome):

@Html.TextBox("myTextBoxName", Model.MyTextBoxValue)
@Html.DropDownList("myDropDownName", Model.MySelectList))

In these cases, the engine doesn't know what types Model.MyTextBoxValue or Model.MySelectList are, therefore it can't figure out what overloads of the extension methods to compile. So you just help it along with some strong typing:

@Html.TextBox("myTextBoxName", (string)Model.MyTextBoxValue)
@Html.DropDownList("myDropDownName", (SelectList)Model.MySelectList))

By the way, just to stop people from potentially pulling out their hair, that SelectList has to be properly instantiated with something like:

var items = List<SelectListItem>();
...
new SelectList(items, "Value", "Text");
like image 27
Milimetric Avatar answered Oct 20 '22 18:10

Milimetric