I am tired to google around and ddn't found the exact answer.
I know I can pass date from view to template by additionalViewData
parameter of .EditorFor()
or .DisplayFor()
but I want a data back from template!
I have Date.cshtml
in my ~/Views/Shared/EditorTemplates/
.
My model property already have something like this:
public class Person
{
[DisplayFormat(DataFormatString = "{0:d}")]
[DataType(DataType.Date)]
public Nullable<DateTime> BirthDate { get; set; }
}
and the view:
@Html.EditorFor(model => model.BirthDate)
Now I want only to load datepicker script when ever the view uses the date template.
So I try to use RequireDatePicker
like this in my template:
@model DateTime?
@Html.TextBox(...)
@{ViewBag.RequireDatePicker = true;}
and in the bottom of _Layout.cshtml
:
@Scripts.Render("~/bundles/jquery")
@if (ViewBag.RequireDatePicker == true)
{
<script type="text/javascript">
if (!Modernizr.inputtypes.date) {
// Todo: use Modernizr.load
$(function () {
$("input[type='date']").datepicker();
});
}
</script>
}
The problem is I just realize ViewBag
/ViewData
has a different context from the view/partial and the display/editor template. What is the best way to do this?
Fix I can pass data from template back to view by route data like this:
@{ViewContext.RouteData.DataToken["requireDatePicker"] = true;}
However I end-up not passing the data but just this:
Have bundle
"~/bundles/jqueryui"
that- remove jquery ui date picker feature from it (and move to
"~/bundles/jqueryui-datepicker"
) - include a
Modernizr.inputtypes.date
check andModernizr.load
to load"~/bundles/jqueryui-datepicker"
- remove jquery ui date picker feature from it (and move to
No need to modify
_layout.cshtml
to check forRequireDatePicker
.@Scripts.Render("~/bundles/jquery")
and@Scripts.Render("~/bundles/jqueryui")
is enough sinecModernizr.load
is already included.No need to pass
RequireDatePicker
fromDate.cshtml
to view or _Layout.cshtml asModernizr.load