Assigning Value to Bootstrap-datetimepicker with Format MM/YYYY Displays Incorrect Year - asp.net-mvc-4

I am using bootstrap-datetimepicker version 4.17.47 in ASP MVC 4 app.
I have this model property:
public DateTime MonthYear { get; set; }
I assign default value in controller (arbitrary value is just an example actual value is determined through some logic):
model.MonthYear = new DateTime(2017, 3, 1);
I display this in view using datepicker so users can update the value as needed:
#Html.TextBoxFor(model => model.MonthYear, new { #class = "form-control input month-picker" })
Script:
$('.month-picker').datetimepicker({
format: 'MM/YYYY',
useCurrent: false,
toolbarPlacement: 'bottom',
viewMode: 'months'
});
The problem is the control displays "03/0001" instead of "03/2017".
What am I missing here?

Apparently the problem is that the input is being filled with a DD/MM/YYYY date from server when datetimepicker is expecting only MM/YYYY. Try formating the textbox, like:
#Html.TextBoxFor(model => model.MonthYear, "{0:MM/yyyy}", new { #class = "form-control input month-picker" })
That should work.

Related

Get data from sql server to appear on Kendo Scheduler

I want to know how I can get the information that I have on a sql table into a Kendo scheduler. What I currently have in the server is the Start, End, StartTimeZone, EndTimeZone, Description, Title... etc. All the stuff you need for Kendo Scheduler, but I have many events that I need to make and put into a calendar format and the scheduler seems like the best way to do it. Right now my calendar view looks like this
#(Html.Kendo().Scheduler<**censored**.Models.LeaveRequest>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView();
views.MonthView(MonthView => MonthView.Selected(true));
})
.Timezone("Etc/UTC")
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.LeaveRequestId);
m.Field(f => f.Title).DefaultValue("No title");
m.Field(f => f.EmployeeId).DefaultValue(1);
m.Field(f => f.Title).DefaultValue("No title");
m.RecurrenceId(f => f.LeaveRequestId);
})
.ServerOperation(true)
.Read(read => read.Action("Read", "Home").Data("getAdditionalData"))
.Create("Create", "Home")
.Destroy("Destroy", "Home")
.Update("Update", "Home")
)
)
<script>
function getAdditionalData() {
var scheduler = $("#scheduler").data("kendoScheduler");
var timezone = scheduler.options.timezone;
var startDate = kendo.timezone.convert(scheduler.view().startDate(), timezone, "Etc/UTC");
var endDate = kendo.timezone.convert(scheduler.view().endDate(), timezone, "Etc/UTC");
//optionally add startTime / endTime of the view
var startTime = kendo.date.getMilliseconds(scheduler.view().startTime());
var endTime = kendo.date.getMilliseconds(scheduler.view().endTime());
endTime = endTime == 0 ? kendo.date.MS_PER_DAY : endTime;
var result = {
Start: new Date(startDate.getTime() - (startDate.getTimezoneOffset() * kendo.date.MS_PER_MINUTE) + startTime),
End: new Date(endDate.getTime() - (endDate.getTimezoneOffset() * kendo.date.MS_PER_MINUTE) + endTime)
}
return result;
}
</script>
<style>
.invalid-slot {
background: red !important;
cursor: no-drop;
}
</style>
</div>
But I don't know what I need to do in the controllers and models, if anything.
I just completed the implementation of KendoUI Scheduler by integrating it with SQL data base. However, I made use of JavaScript API to do so in my MVC project.
To load the data i.e. "read" and perform insert, update and delete just return the model in JSON format from controller. The Scheduler will bind the data for you, if it gets the "know" format.
return Json(**censored**.Models.LeaveRequest, JsonRequestBehavior.AllowGet);
Couple of important points:
1. KendoUI Scheduler depends a lot on unique id, so in case you have anything other than "id" - then "do" configure it in your scheduler.
In JS API it was done using following syntax, where EventID was the unique ID my SQL table.
schema: {
model: {
"id": "EventID",
"fields": {
"EventID": {
"type": "number"
},
....
Always return JSON data from your Insert, Update and Delete method from Controller. For instance:
public JsonResult UpdateCalendarEvent(string models)
{
...
return Json(censored.Models.LeaveRequest, JsonRequestBehavior.AllowGet);
}
In case of Insert, before returning the JSON object, do update the ID or EventID with latest row id, so Scheduler will sync up all data on client side and can perform update and delete operation appropriately.
Hope that helps!

Display value of datetime in textboxfor at edit time

I am using HTML5 type = "date" and it's working fine.
But when there is type="datetime-local", at the time of editing field it's not displaying using TextBoxFor() in MVC4
This one is working,
#Html.TextBoxFor(c => c.date, "{0:yyyy-MM-dd}", new { #class = "form-control",#placeholder = "DateTime", #type = "date" })
in texbox = "2/15/2015"
but
#Html.TextBoxFor(c => c.datetime, "{0:yyyy-MM-dd HH:mm:ss}", new { #class = "form-control", #placeholder = "OpeningDoor", #type = "datetime-local" })
not displaying data when there is value in "datetime".
textbox = "mm/dd/yyyy _:_:_" instead of "1/15/2015 01:40:00 PM"
The format string needs to be "{0:yyyy-MM-ddTHH:mm:ss}" or you can simply use "{0:s}"
#Html.TextBoxFor(c => c.datetime, "{0:s}", new { #class = "form-control", placeholder = "OpeningDoor", type = "datetime-local" })
Side note: type="date" and type="datetime-local" are only supported in Chrome (a normal textbox will be generated in FireFox and IE) so you should consider using a jquery plugin. Refer browser comparison.

How to assign null/string to an int type in MVC Razor using Entity Framework?

I am using a simple MVC 4 application using Entity Framework.
In my View I am displaying data from of a table using webgrid.
View Also has Textboxes(EditorFor) for saving any new record in the table.
I am using partial view for the Textboxes, as in the beginning when the page is launched, the textboxes should remain empty.
Out of 5, two columns are of integer types.
In order to make the textboxes empty initially I am using a new object as -
#if (!dataGrid.HasSelection)
{
Datamodel = new EntityFrDemo.Models.FacultyDetails { DepartmentID = 0, Name = "", Subject = "", YrsExp = 0, Email = "" };
Html.RenderPartial("~/Views/Shared/_FacultyDetails.cshtml", Datamodel);
}
//------------------------------------------------------------------------
#Html.LabelFor(model => model.DepartmentID)
#Html.EditorFor(model => model.DepartmentID)
#Html.ValidationMessageFor(model => model.DepartmentID)
//-----------------------------------------------------------------------------
So I am able to make my boxes empty, however for the Integer type boxes '0' is coming, as I can only assign zero.
So How can I override/superimpose the integer value type boxes to empty string type so that boxes remains empty only in case when no row is selected i.e. in initial stage...?
When you use #Html.EditorFor() with a int value, Razor generate a html tag like this
<input type="number" name="propertyName" id="propertyName" value="propertyValue" />
If you didn't set a value for the int property, the default int value is zero. To set another value in the html tag, you can write it without Razor or you can set the value like the code below.
#Html.EditorFor(model => model.DepartmentID, new { htmlAttributes = new { #Value = "" } })
Note: It is capital "V", not a lower case "v".

Select a default value in dropdownlistfor MVC 4

I'm trying to make a dropdownlistfor with a selected value but it doesn't work :/ And I search on the web but I don't find the solution :/
For the moment, I'm doing this :
In C# :
ViewBag.ID_VEH = new SelectList(db.VEHI, "ID_VEH", "COD_VEH", 4); // 4 is an example
In my cshtml :
#Html.DropDownListFor(model => model.ID_VEH, ViewBag.ID_VEH as SelectList)
The dropdownlist is well complete but the default value is not selected :/ do you have an idea please ?
What I like to do is add a list of the items to display in the dropdownlist to my model, so I don't have to pass that list via a viewbag.
Also i like to add a field to my model that contains the SelectedValue, that I fill in the controller
Then you can do
#Html.DropDownListFor(model => model.ID_VEH, new SelectList(Model.listVEH, "ID_VEH", "COD_VEH", Model.SelectedVEH_ID), "--Select VEH--")
just set the initial value of model.ID_VEH to 4:
In the controller:
model.ID_VEH = 4;
Just in case someone has similar problems finding the answer:
I want to have view with the dropdown boxes have focus on the items i give (hardcoded) in the controller:
Controller:
SGLDataRegistration.Models.DataRegistrationModel mdl = rwd.GetData(DateTime.Now.Year, currentWeek, DateTime.Now, 139, 1);
View:
<div id="tempCustomerselect">
#Html.LabelFor(m => m.CustomerName)
#Html.DropDownListFor(m => m.PitchID, new SelectList((new SGLDataRegistration.Models.CustomerModel().GetRoles()).OrderBy(x => x.CustomerName), "PitchID", "CustomerName"), new {id = "ddlCustomer", #class="jsddlCustomer"})
</div>
In this GetData, i setthe desired values hardcoded:
public SGLDataRegistration.Models.DataRegistrationModel GetData(int year, int weekNumber, DateTime datum, int pitchID, int parameter)
{
try
{
DataRegistrationParameters drp = GetParameter(parameter);
//vul een instantie van het dataregistrationmodel
SGLDataRegistration.Models.DataRegistrationModel drm = new Models.DataRegistrationModel();
drm.WeekNumber = weekNumber;
drm.BeginDay = datum;
drm.Parameter = parameter;
drm.Year = year;
drm.PitchID = pitchID;

How can I validate a currency field?

I have an ASP.NET MVC-4 application with this currency field:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}", ConvertEmptyStringToNull = true)]
[DataType(DataType.Currency)]
public decimal? Price { get; set; }
This is the corresponding part in my view:
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
If the price is 100 Euro the text field in the view shows:
100,00 €
This is nice.
But I am having problems as soon as I try to do a Postback. The validator pops up and says that the price field needs to be a number.
I can only fix this if (1) I delete the € symbol and (2) replace the decimal separator (replace comma with a dot).
If there is no better solution, I guess I could change the DataFormatString = "{0:F2}" in order to avoid the currency symbol.
But how do I make the validator accept the comma as decimal separator instead of the (American) dot?
Thanks for your help, guys!
So, I was able to solve my problem with jQuery's Globalization plugin from http://github.com/jquery/globalize.
I added the following files to my /scripts folder:
/scripts/globalize.js
/scripts/cultures/globalize.cultures.js
/sctipts/cultures/globalize.culture.de-DE.js
In BundleConfig.cs:
bundles.Add(new ScriptBundle("~/bundles/scripts/globalization").Include(
"~/Scripts/globalize*",
"~/Scripts/cultures/globalize*"));
In _Layout.cshtml:
#Scripts.Render("~/bundles/scripts/globalization")
and in the script section of _Layout.cshtml:
$.validator.methods.number = function (value, element) {
return this.optional(element) || !isNaN(Globalize.parseFloat(value));
}
$.validator.methods.range = function (value, element, param) {
return this.optional(element) || (Globalize.parseFloat(value) >= param[0] && Globalize.parseFloat(value) <= param[1]);
}
However, I couldn't make the currency symbol to work with the client validation, so I also changed the data annotation as follows:
[DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:c}", ConvertEmptyStringToNull = true)]
But that was it. No other changes necessary. I can now enter values like "1,49" or "18,77" and everything gets stored properly in my database.