1

Hi I have a MVC create with:

<div class="editor-label">
            @Html.LabelFor(model => model.Date)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Date)
            @Html.ValidationMessageFor(model => model.Date)
        </div>

I hooked this up to be a jquery datepicker.

I then decided I wanted the datepicker to be inline like:

http://jqueryui.com/demos/datepicker/#inline

It says to do this you need to call .datepicker() on a div instead of an input.

Ok, that's fine but I guess that means I can't use @Html.EditorFor any more?

Would anyone know how to achieve this for MVC?

2 Answers 2

2

You could use a hidden alternate field:

<div class="editor-label">
    @Html.LabelFor(model => model.Date)
</div>
<div class="editor-field" id="datepicker">
    @Html.HiddenFor(model => model.Date)
    @Html.ValidationMessageFor(model => model.Date)
</div>

and then:

$('#datepicker').datepicker({
    altField: "#Date",    
});

or keep the @Html.EditorFor(x => x.Date) in your view and decorate your view model property with the [HiddenInput] attribute:

[HiddenInput]
public DateTime? Date { get; set; }
Sign up to request clarification or add additional context in comments.

4 Comments

thanks that's a really cool solution. I did though still want the input text box to be there as well though.
@AnonyMouse, cool, then keep the EditorFor instead of making a hidden field.
This doesn't seem to work at all with MVC5 and jquery-ui-1.8.23. Still looking for a way to do this...
Um actually it does work. I wrote the startup function but neglected to actually call it - had to add $(startup); - egg on my face...
0

You can create DateTime file in EditorTemplates folder and map container div with hidden input field. You would have something like this in editor template file for DateTime type:

@model DateTime
@{
    var inputId = this.ViewData.ModelMetadata.PropertyName;
    var containerId = this.ViewData.ModelMetadata.PropertyName + "_container";
}

@Html.HiddenFor(x=>x)
<div id="@containerId"></div>
<script type="text/javascript">
    $("#@containerId").datepicker({
        onSelect: function (dateText, inst) {
            $("#@inputId").val(dateText);
        }
    });
</script>

Then you can use EditorFor syntax as you did before. See http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx for info on editor templates.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.