Inconsistent date format across browsers/servers [duplicate] - asp.net

I'm a server side guy trying to teach myself a bit of CSS, Javascript, jQuery etc. I have written a little test project that loads up a model and displays the values in simple text boxes. Works OK, as you can see:
But of course, I want to display those dates appropriately. So let me change those input types to "date". Here's the Razor code:
#Html.TextBoxFor(m => m.Date, new { #type="date", #id="ondate" })
Well, that worked.... sort of. I mean, it now displays as a date picker... but it's no longer displaying the model's date!
What am I doing wrong?

The type="date" attribute renders the browsers HTML5 datepicker. In order for this to work correctly, the format needs to be yyyy-MM-dd (ISO format), so it needs to be
#Html.TextBoxFor(m => m.Date, "{0:yyyy-MM-dd}", new { #type="date" })
Alternatively you can set data attributes on the property
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime Date { get; set; }
and use
#Html.EditorFor(m => m.Date)
which adds the type="date" attribute and uses the correct format.
Side notes:
The HTML5 datepicker is only supported in recent versions of Chrome
Using EditorFor() (in MVC-4) will not allow you to set the id
attribute, but its not clear why you would need to change the
default id="Date" to id="ondate"

Try this:
<%= Html.TextBoxFor(m => m.Date, new { #type = "date", #id = "ondate", #value = Model.Date.ToString("mm/dd/yyyy") })%>

Related

Date from Model does not display in TextBoxFor

I am using Html.TextBoxFor to set and display dates from Model. They work fine when setting the values, however when I retrieve values from the database, they do not display the dates:
Here is my HTML:
#Html.TextBoxFor(x=>x.effectiveDate, "Select Effective Date", new {#class="date form-control", id= "reqEffectiveDate" })
If I switch to #Html.EditorFor, the dates display, but the element no longer displays like the other "form-control" elements on the page, and clicking in the box no longer displays the datepicker:
EditorFor doesn't apply any CSS classes by default, unless you have defined a custom editor template.
You need to pass a collection of HTML attributes to the editor:
#Html.EditorFor(x => x.effectiveDate, new { htmlAttributes = new { #class = "date form-control", id = "reqEffectiveDate" } })

MVC: How to get date time value to edit

I want to set editable a date time in Edit page. As you can in the image the other datas shown in the fields, date time value is not shown. Here is my code to show date time value :#Html.TextBoxFor(model => model.CommunicationTime, new { Value = Model.CommunicationTime, type = "date" })
I am sure of my date time value is not empty. What should I do?
Use jquery datepicker then change your TextBoxFor like below:
#Html.TextBoxFor(model => model.CommunicationTime, new {#id = "yourdatepicker", #Value = Model.CommunicationTime.Value.ToString("MM/dd/yyyy")})
<script>
$('#yourdatepicker').datepicker();
</script>
Do you want a date or datetime? As an HTML5 input type, datetime is only supported in Opera and Safari. Otherwise, you'd need to use jquery datepicker and a timepicker.
You should change type to datetime like this : type = "datetime"
#Html.TextBoxFor(model => model.CommunicationTime, new { Value = Model.CommunicationTime, type = "datetime" })

TextBoxFor producing a blank field

I have a weird problem in my MVC app.
When the user selects a date from a drop down, it clears the StartDate and EndDate fields.
I have the following fragment of code:
<label>Start date: #Model.StartDate</label>
#Html.TextBoxFor(s => s.StartDate)
The weird thing is that you can wee where I'm outputting it in the label, the date comes out there. The textbox is unpopulated.
I've checked the produced markup and the textbox is not being populated.
<label>Start date: 19/05/2013</label>
<input id="StartDate" name="StartDate" type="text" value="" /> <br />
What am I missing here?
To add a little bit more information, when the page is initially populated the default start and end date are output. There is a bit of jQuery that empties those fields when a <select> is changed. If I comment that bit out then the fields retain their previous values as opposed to blank. Essentially, whatever is submitted to the server is output rather than the value in the model.
Essentially, whatever is submitted to the server is output rather than the value in the model.
This behaviour is actually by design. The idea being that generally the user would expect to see in the text box what they submitted to the server.
See here for a detailed explanation, and a work around.
Instead of doing this
<label>Start date: #Model.StartDate</label>
#Html.TextBoxFor(s => s.StartDate)
You should do this
<label id="someId"></label>
#Html.TextBoxFor(s => s.StartDate,new{#id="startdate"})
and using jquery on change event on your textbox you can set lablel
$("#startdate").change(function(){
var date="Start Date:"+$(this).val();
$("#someid").html(date);
});
Thinks that your model is a class named What like this:
public class What
{
public string StartDate { get; set; }
}
Then, think that your application is "MyApplication", you need to add to the view as if the view is stronglytyped:
#using MyApplication.Models;
#inherits System.Web.Mvc.WebViewPage<What>
Then all should we run as you expect

Vary type of input control based on drop down selection?

I'm building an edit screen where a use can edit rows of data. One of the fields is represented by a drop down, and another is an input field named 'value'. Now, depending on the value in the dropdown, I need to have different kinds of input controls for the value input control. Sometimes it should be a text box, others a datetime control (html5 and / or jqUI date picker), and finally a dropdown list containing a fixed set of values ('Yes' / 'No').
So basically sometimes I need to accept any string data, sometimes a date, and sometimes a boolean (but with a select box, not a check box). What's my best option for implementing this? Ideally the value entered would not be lost moving from one kind of input to another, while the user is on this edit page. On post back, I have a single database value to store (its a sql_variant).
Also, I'm using asp.net mvc3 so an ideal solution will work with the normal Html.ValidateFor and Html.ValidationMessageFor methods.
After lot's of time in JSFiddle, I made this solution. And I think it's pretty cool. It wasn't really that hard. and you can adapt it to whatever you need. just click here.
basically I make variables to represent the possible values. then I make a variable to hold the active element.
Whenever the type selector changes, it calls the change() function which uses if() statements to check what was selected, and then it sets the active element accordingly.
And finally, it calls the hide() function which hides the inactive elements.
here is the updated version
RED ALERT: I realized this didn't work in FF (maybe it was just my browser but whatever).
so I fixed it here
The typical way I accomplish something like this is to actually store 3 different fields in the db for each of the different types of values. Then I create something like the following html:
<!-- Input type selector -->
<div class="cell variable-selector">
<select><option ...</select>
</div>
<!-- varied input -->
<div class="cell variable show-text">
<div class="text"><input type="textbox"></div>
<div class="date-picker"><input type="textbox" class="datepicker"></div>
<div class="drop-down-bool"><select><option ...</select>
</div>
Then I have css that hides or shows the correct input element based on which class the cell has:
div.variable div { display:none }
div.show-text div.text { display: inline }
div.show-date-picker div.date-picker {display: inline }
div.show-drop-down-bool div.drop-down-bool {display: inline}
lastly you can setup some javascript so that when you change your variable-selector you change the class of your variable cell. Which jquery one might do this as so:
$(document).ready(function() {
var variableSelector = $("div.variable-selector > select");
variableSelector.change(function() {
var type = $(this).text();
var class = "cell variable show-" + type;
var variableCell = $(this).parent().parent().find("variable");
variableCell.attr("class", class);
})
});
As a quick warning I wrote the above code on the fly in the stack overflow editor window so there might be a couple of syntax errors or a minor bug somewhere but the basic idea should work. Hope it helps.
--Adam
In case you want to make full use of mvc3 validations, consider this approach.
Model
public class MultiValueViewModel
{
[Required]
public string TextValue { get; set; }
[Required]
public bool? BooleanValue { get; set; }
public MultiValueType ValueType { get; set; }
}
public enum MultiValueType
{
Text,
Boolean
}
View
#model MultiValueViewModel
#Html.DropDownListFor(m => m.ValueType, new SelectList(new[]
{
MultiValueType.Text,
MultiValueType.Boolean
}), new { #id = "multi_value_dropdown" })
<p>
<div data-type="#MultiValueType.Text" class="multi-value-pane">
#Html.EditorFor(m => m.TextValue)
</div>
<div style="display: none" data-type="#MultiValueType.Boolean" class="multi-value-pane">
#Html.DropDownListFor(m => m.BooleanValue, new SelectList
(new [] {
new SelectListItem { Text = "Yes", Value = "true"},
new SelectListItem { Text = "No", Value = "false"}
}, "Value", "Text"), optionLabel: "[Not Set]")
</div>
</p>
Javascript:
<script type="text/javascript">
$(function () {
$("#multi_value_dropdown").change(function () {
var value = $(this).val();
$(".multi-value-pane").each(function () {
$(this).css("display", value == $(this).attr("data-type") ? "block" : "none");
});
});
})
Inside your controller, receive MultiValueViewModel value (alone or inside parent model), and based on selected ValueType save to database. Please note that you will need jquery.validate version 1.9 if you need to skip validation on hidden fields (e.g. :hidden).

ASP.NET mvc: How to automatic fill the date field with today's date?

Assume that a model has a datetime datatype.
So in view there will be a blank field ask you to input datetime.
Is there a way to fill this HTML field with today's date/datetime as default value?
model.SomeDateField = DateTime.Now();
return View(model);
Simple
<%: Html.TextBox("date", DateTime.Now.ToShortDateString()) %>
Or use javascript to get the client's browser date. Better yet use jquery's datepicker for nice UI for selecting dates. With it you can also prepopulate the default date:
/**
Enable jquery UI datepickers
**/
$(document).ready(function () {
$(function () {
$(".date-select").datepicker({ dateFormat: 'dd.mm.yy' });
$(".date-select").datepicker($.datepicker.regional['sl']);
});
$(function () {
$("#someDateField").datepicker('setDate', new Date());
});
});
Wanted to add what I found that I needed for filling a datepicker with today's date that was being generated from the DateTime data type in HTML5 (via razor at the view in the value attribute) which is this:
#Html.TextBoxFor(model => model.YourDateInModel, new { #id = "YourDateId", #type = "date",
#Value = DateTime.Now.ToString("yyyy'-'MM'-'dd") })
Note that the ToString() format was necessary to get it to show the date in the datepicker field (it requires a database format).
Source: https://forums.asp.net/p/2154640/6320474.aspx?p=True&t=637376668781782563
Edit: This ended up leaving the database blank/null by itself, so I also had to set the model with the initial value of today's date (as mentioned above).
public DateTime YourDateInModel { get; set; } = DateTime.Now;
In my case I needed both. It may also be helpful to use something like:
$("#YourDateId").prop("disabled", true);
If you are using JQuery/Javascript to prevent changes to the field where applicable.

Resources