Mudblazor DatePicker binding works one way only - blazor-server-side

I have been trying to bind mudblazor datepicker to a DateTime property using Date.
<MudDatePicker Label="Start Date" Date="#StartDate" />
<MudTextField Label="SelectedDate" #bind-Value="#StartDate" />
<MudText Typo="Typo.h3">Selected Date is: #StartDate</MudText>
#code
{
public DateTime StartDate { get; set; }
public string DateString { get; set; }
}
I have tried this code on their site and in visual studio
The code will update the Date Picker and my Text output when leaving the text field, this is normal behavior. However, I want to change the Text based on my selection of Date picker. I have tried binding to date and value. both don't reflect the selection I have made.
I have checked the documentation on their site and there is nothing on how to handle binding beyond what I am doing.
If any one knows how to bind Date picker in mudblazor please help.
Thanks

for anyone interested here is the answer:
A Date picker in Mudblazor will only bind to a nullable DateTime, and I have to use #bind-Date. So my sample code that should work looks like this:
<MudDatePicker Label="Start Date" #bind-Date="#StartDate" />
<MudTextField Label="SelectedDate" #bind-Value="#StartDate" />
<MudText Typo="Typo.h3">Selected Date is: #StartDate</MudText>
#code
{
public DateTime? StartDate { get; set; }
}

I was having a similar issue with MudDateRangePicker.
I found that I could use a nullable or a non-nullable DateRange variable but if I wanted to get the currently selected Start & End dates from a callback function, I would have to call the DateRangePicker.Close() method before I checked the dates.
Just FYI if anyone else is looking at this issue.

Related

DateTime Field is not showing dateTime picker on MVC page [duplicate]

I am trying to populate #Html.EditorFor helper. I have created a view model with the below property
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }
and my helper is set up as below (a)
#Html.ValidationMessageFor(m => m.YearBought)
#Html.EditorFor(model => model.YearBought, new { #type = "date" })
I have also tried (b)
#Html.ValidationMessageFor(m => m.YearBought)
#Html.EditorFor(model => model.YearBought.Value.Date)
Using the above format (a) nothing is displayed. Using the above format (b) 12/05/2014 00:00:00 is displayed in textbox format.
I am trying to achieve a datepicker format without a time displayed
I have reviewed several other questions but cant see what i've done different.
When I look in my database, the value is save as 2014-05-12 and when I am saving the value the EditorFor helper generates the required input facility
questions reviewed
first second third....the list goes on
EDIT
just opened the console in chrome dev tools and so this message
The specified value "12/05/14" does not conform to the required format, "yyyy-MM-dd"
I thought DisplayFormat(DataFormatString = "{0:dd/MM/yy}" was defining how to display my date?
You need to use the ISO format when using type="date"
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }
This will display the date in the browsers culture.
Note there is no need to add #type = "date". The EditorFor() method will add that because of the DataType attribute. Note also that type="date" is only supported in Chrome (FireFox and IE will just generate a normal textbox)
If you do want to display the format dd/MM/yyyy in a standard textbox then you can use
#Html.TextBoxFor(m => m.YearBought, "{0:dd/MM/yyyy}")
As it says in Stephen's answer, you have to make your formats match between the tags in your model to what is shown in the View, and it should be of the yyyy-MM-dd (ISO) format, regardless of how you actually want to display the date:
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
// .... your namespace .... your class....
[DisplayName("Year Bought")]
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }
And he's right, because we have [DataType(DataType.Date)], we don't need #type = date in our HtmlAttributes on the View.
Where my answer differs from his is how to actually apply the value from the Model to the control on the View. Since YearBought is a Nullable<DateTime>, we have to set it with its value a certain way, using .Value:
#Html.EditorFor(model => model.YearBought,
new { htmlAttributes = new { #class = "form-control datepicker",
#Value = Model.YearBought.Value.Date.ToString("yyyy-MM-dd") } })
Paying close attention to set the .ToString("yyyy-MM-dd"). It's not going to display in the box like that, though - at least for me - probably because my U.S. Regional settings on my computer take over and display it as MM/dd/yyyy regardless. This might confuse some, but it's better to just "do" and not worry about it.
If YearBought was just a straight DateTime instead of a DateTime?, it would be without the .Value:
#Html.EditorFor(model => model.YearBought,
new { htmlAttributes = new { #class = "form-control datepicker",
#Value = Model.YearBought != null ?
Model.YearBought.Value.Date.ToString("yyyy-MM-dd") : null } })
I would make your view model's YearBought property a String for the easiest manipulation. The server can format the date, it can do the parsing on postback, and you can still use the DataType.Date data annotation for jQuery validation. This also ensures that the display value will be exactly what you want prior to being submitted to the view.
Alternative to the HTML type attribute, you can use an EditorTemplate in MVC to put the markup, CSS, and JS needed to render a custom editor for a known C# datatype like DateTime.
Here is a walkthrough for creating a custom 'EditorTemplate' in MVC (although not for a Date data type, but concept is the same)

DateTime field internal format

I have an ASP.NET Core MVC 1.0 app and inside of it a model that contains a DateTime field:
[Display(Name = "Date of Delivery"), DataType(DataType.Date)]
public DateTime? DateOfDelivery { get; set; }
In my Details.cshtml I refer to this field as usual:
#Html.DisplayFor(model => model.DateOfDelivery)
Depending on where I am, the output of this field differs! If I am testing on my local machine, the output is:
20.03.2017
on my on Azure deployed Website, it is:
3/20/2017
These different formats bring me into big trouble, as I am using a datepicker to fill the field in my Create/Edit controllers.
I also tried to set the date format explicit:
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true), Display(Name = "Date of Delivery"), DataType(DataType.Date)]
public DateTime? DateOfDelivery { get; set; }
This displayed an uniform date (20.03.2017) on both, local machine and Azure. But still the inputs that are accepted differ. Local:
20.03.2017
And on Azure:
03.20.2017
What can I do to ensure, that the accepted dateformat on both, my local machine and also on Azure, are the same? I already read a lot of Stackoverflow questions regarding date topics, but none was able to help me.
You can use #Html.TextBoxFor(model => model.DateOfDelivery, "{0:dd.MM.yyyy}") as in this post post

dbcontext.savechanges always saves default Value

I have a SQL-Azure database created with Entity Framework 6.1, Code-First.
The "datetime" field in my 'EmazeEvents' table was created like this:
datetime = c.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()")
and defined like this in the code:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Index]
public DateTime datetime { get; set; }
I understand this means that in case this field is omitted in insertion, it will get by default the insertion date, which indeed it does.
However, I am having trouble inserting rows that set this field. Although I set the value of the appropriate variable, it still writes to the database the default date.
Some code extractions:
EmazeEvents is defined like this:
public class EmazeEvents:DbContext
{
public EmazeEvents()
: base("EmazeEvent")
{ }
public DbSet<EmazeEvent> events { get; set; }
}
}
What I do is:
context = new EmazeEvents();
EmazeEvent e = new EmazeEvent();
// e.datetime does get the correct date
e.datetime = DateTime.ParseExact("2014-05-31T00:00:06.8900000", "O", CultureInfo.InvariantCulture);
context.events.Add(e);
context.SaveChanges();
The record written to the database has the current date-time, ignoring the one in e.datetime.
I found out that the problem was with the definition of the 'datetime' field. When I removed the:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
It started letting me write other values than the default.

MVC4 Html.DropDownListFor is not selecting specified value

I have the following classes:
public class PreviewImage_Edit
{
...
public List<GridDetail_Edit> GridDetails { get; set; }
public SelectList GridDetailTypesList { get; set; }
...
}
public class GridDetail_Edit
{
...
public int GridDetailTypeId { get; set; }
...
}
And, I have a partial view that expects a model of type PreviewImage_Edit, which has the following block of code:
#model PreviewImage_Edit
...
#if (Model.GridDetails != null)
{
for (var i = 0; i < Model.GridDetails.Count(); i++)
{
...
#Html.DropDownListFor(model => model.GridDetails[i].GridDetailTypeId, Model.GridDetailTypesList)
...
}
}
I am properly creating the SelectList in GridDetail_Edit and the dropdown is populating as expected. Below is the markup that is generated for the first GridDetails object:
<select data-val="true" data-val-number="The field GridDetailTypeId must be a number." data-val-required="The GridDetailTypeId field is required." id="GridDetails_0__GridDetailTypeId" name="GridDetails[0].GridDetailTypeId">
<option value="1">Top</option>
<option value="2">Bottom</option>
</select>
I've verified that the selected choice is properly saved in the database (even when the selected option isn't the first/default option in the dropdown) when the Save button is clicked. However, when I go back to re-edit, the selected option continues to be the first option in the dropdown.
I stepped through the code and verified that the data is properly retrieved from the database. I've even gone so far as converting the Html.DropDownListFor to Html.EditorFor and confirmed that the value stored in the database is making it to the view as expected.
I've used Html.DropDownListFor when the property associated with it was an integer value but never when it's an integer value that's part of a collection of objects. I would be apprehensive about what I've done so far, but everything appears to be working with this one key issue.
So far, I've tried moving the SelectList in PreviewImage_Edit into GridDetail_Edit and initializing them separately where I've programmatically set the "Selected" value for the appropriate SelectedListItem. That didn't work... same result.
Has anyone come across this issue? Any suggestions on the best way to resolve this?
Update
Below is the snippet of code that populates GridDetailTypesList
var gridDetailTypes = _db.GridDetailTypes.OrderBy(g => g.DisplayOrder).ToList();
return new SelectList(gridDetailTypes, "GridDetailTypeId", "Name");
It's pretty straightforward. The second parameter of the SelectList constructor represents the field whose values should be used in the "value" attribute. I don't believe the issue is related to the fact that the value field is an integer as I have similar code on the same page and that dropdown is functioning properly. The only difference is that my "problem" dropdowns are within a collection of my ViewModel.
The only time I've seen messages on a dropdown about "must be a number" was when I screwed up and the (numeric) value of the OPTIONs were being padded with spaces when I loaded them from a database. This doesn't appear to be your problem (and your example specifically shows no padding) but I would definitely want to look at the value of GridDetails[0].GridDetailTypeId to make sure it was of the correct type/value.
Wish I could add this as a comment rather than an answer - but my rep isn't high enough yet...
The only way it works for me is when my List is a simple IEnumerable<string>, or when I pass the same property of my custom object for both the DataText as the DataValue. As follows:
Html.DropDownListFor(m => m.TypeOfFilter, new SelectList(Model.Filters, "DataText", "DataText")
where TypeOfFilter is an enum and Model.Filters is a List<MySelectItemModel>.
That way you can see in the generated HTML that the right option is selected.

MVC fields not required but user being told they are

Title says it all. The model does not require the StartDate field but on POST I'm told it's required. It's one of several search fields, each one optional. Due to that, I'm not checking IsModel.Valid so the search works anyway, but the message shows up onscreen. If I set, in the view, #Html.ValidationSummary(true), that hides the message but the field still turns red.
Also, I do have a check to make sure EndDate is later than StartDate, so I need the messages for errors /requried fields to show up, just not when there ISN'T an error.
Here's the code:
MODEL (Partial)
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[Display(Name = "End Date")]
[GreaterThanOrEqualTo("StartDate", ErrorMessage = "End Date must be later than Start Date")]
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
VIEW (partial)
#using (Html.BeginForm()){
#Html.ValidationSummary(false)
<table>
<tr>
<td>
#Html.DisplayNameFor(m => m.StartDate)
#Html.TextBox("StartDate", "", new { #class = "datefield" })
etc.
SHARED/DISPLAY TEMPLATES
#model Nullable<DateTime>
#(Model != null ? string.Format("{0:M/d/yyyy}", Model) : string.Empty)
SHARED/EDITOR TEMPLATES
#model Nullable<DateTime>
#{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime) Model;
}
#Html.TextBox("", String.Format("{0:M/d/yyyy}", dt.ToShortDateString()), new { #class = "datefield", type = "date" })
}
Some of these editors are to make a pop-up calendar work, btw.
I've tried turning on/off various things and one way or another, it still says the date fields are required. Any ideas? Thanks.
Easy way to remove validation is make int Null-able, I have already tested and it works fine. here is example:
public int? Id { get; set; }
As mentioned in the comments, value types like DateTime, int, decimal, etc. are treated as required if you don't make them nullable.
If the GreaterThanOrEqualTo attribute doesn't come from a library (such as MVC Foolproof Validation), you should let it return true if both Startdate en Enddate are null. Else you woud have to write your own custom validation attribute, but it's not that hard to do.