Display value of datetime in textboxfor at edit time - asp.net-mvc-4

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.

Related

Assigning Value to Bootstrap-datetimepicker with Format MM/YYYY Displays Incorrect Year

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.

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!

How to dynamically populate a Picker using Alloy with Appcelerator?

Is there a way to populate a picker dynamically? This works for option dialogs:
view.xml:
<OptionDialog id="distributionPointsOptionDialog">
<Options>
<Option id="{dp}"></Option>
</Options>
</OptionDialog>
controller.js:
var dp = [];
for (var j in _data) {
if (_data[j].country == country) {
dp.push(_data[j].city + "-" + _data[j].dp_name);
}
}
$.distributionPointsOptionDialog.options = dp;
Is there a way to do the same for a multi-column picker? I tried unsuccessfully to populate a single-column picker.
controller.js:
var fs = Ti.Filesystem;
var installedFonts = fs.getFile(fs.resourcesDirectory+ "/fonts").getDirectoryListing();
Ti.API.info("list of resourcesDirectory fonts: " + JSON.stringify(installedFonts));
var fonts = [];
for (var j in installedFonts) {
fonts.push(installedFonts[j]);
}
$.testPicker.column = fonts;
views.xml:
<Picker id="testPicker" selectionIndicator="true" height="Ti.UI.SIZE" width="70%" visible="true" zIndex="200" useSpinner="true">
<Column>
<Row title="{fonts}"></Row>
</Column>
</Picker>
This results in an error:
ERROR] : message = "undefined is not an object (evaluating '$model.__transform')";
There are couple of wrong things with your implementation.
useSpinner property has been deprecated, so please remove that from your code.
The way you are implementing Options & Pickers is a process of Alloy-Model binding.
For dynamic Options, you can simply use below code:
<OptionDialog id="distributionPointsOptionDialog"></OptionDialog>
$.distributionPointsOptionDialog.options = ['Helvetica', 'Arial', 'Times New Roman'];
<Option id="{dp}"></Option> - this syntax is used for Model data binding
For Picker, use below code:
var fonts = [];
fonts[0]=Ti.UI.createPickerRow({title:'Helvetica'});
fonts[1]=Ti.UI.createPickerRow({title:'Arial'});
fonts[2]=Ti.UI.createPickerRow({title:'Times New Roman'});
fonts[3]=Ti.UI.createPickerRow({title:'Georgia'});
$.testPicker.add(fonts);
OR
var column = Ti.UI.createPickerColumn();
column.add( Ti.UI.createPickerRow({ title: 'Helvetica' }) );
column.add( Ti.UI.createPickerRow({ title: 'Arial' }) );
column.add( Ti.UI.createPickerRow({ title: 'Times New Roman' }) );
column.add( Ti.UI.createPickerRow({ title: 'Georgia' }) );
$.testPicker.columns = [column];
For Pickers, in short, you can either use $.testPicker.add() method, or you can set columns like this $.testPicker.columns = [column1, column2, column1, ...]
Read more here How to add Columns or Rows in Pickers
or
How to add column(s) in Picker

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;