sending js value as parameter to js function - c#

I have posted question here and answer is correct but I'm was not perfectly clear. On the init page load everything is ok, but I need to call with date parameter as argument.
So this is fine
$('#myDate').click(function () {
var date = getDate();
})
but I should send this date to
$('#dataTable').dataTable({
...
Update
Ok, I'm simplifying this,
$('#dataTable').dataTable({
...
on page load takes myDate value and sends this value to the controller. This is fine. Problem is when after page load user pick some other date, I want again to send this data value to the $('#dataTable').dataTable({..
Hope this helps, thanks
function getDate() {
var date = $('input[name="myDate"]').val();
return date;
};
$('#myDate').click(function () {
var date = getDate();
return date;
});
$('#dataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "/Home/Ajax",
"fnServerParams": function (aoData) {
var date = getDate();
aoData.push({ "name": "myDate", "value": date });
},

Maybe something like this?
function getDate() {
var date = $('input[name="myDate"]').val();
return date;
}
$('#myDate').click(updateDate);
function updateDate() {
$('#dataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "/Home/Ajax",
"fnServerParams": function (aoData) {
var date = getDate();
aoData.push({ "name": "myDate", "value": date });
},
//... I assume there's more
}
updateDate();

Related

/Date(1537909200000)/ I having date formatting issue in 'AngularJS'

I can't display the date in the list in json format. How should I follow a path. My angular js knowledge is not good but I need to use it.
HtmlPage
<tbody ng-init="GetAllMatches()">
<tr ng-repeat="m in filteredlist =(matches.data
| filter:filterlist)
| orderBy:sort:reverse
| pagination: currentPage : numPerPage"
ng-if="gamePlayed">
<td>{{m.HomeTeamName}}</td>
<td>{{m.AwayTeamName}}</td>
<td>{{m.StadiumName}}</td>
<td>{{m.Referee}}</td>
<td>{{m.Weather}}</td>
<td>{{ m.StartDate}}</td>
</tr>
</tbody>
.netMVC
var matches = await AppService.MatchService.GetMatchesAsync();
return Json(new { data = matches }, JsonRequestBehavior.AllowGet);
JS
$scope.GetAllMatches = function () {
$http({
method: "GET",
url: "/Match/GetAllMatchAsync"
}).then(function (response) {
$scope.matches = response.data;
}, function () {
alert("error");
});
};
View
/Date(1537909200000)/
Solved
I haven't found any information on your problem, but...
As a solution:
{{m.StartDate.slice(6, -2) | date: 'yyyy-MM-dd HH:mm:ss' }}
Why is your API not returning dates in ISO 8601 format? If you return strings in ISO 8601 format then you just wrap your field function like this
function parseISO8601Date(dateStr) {
return new Date(dateStr);
}
If you really can't change API to return proper ISO 8601 formatted date strings then maybe this blog entry will help you https://weblog.west-wind.com/posts/2014/Jan/06/JavaScript-JSON-Date-Parsing-and-real-Dates
Here is if link dies
if (window.JSON && !window.JSON.dateParser) {
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
JSON.dateParser = function (key, value) {
if (typeof value === 'string') {
var a = reISO.exec(value);
if (a)
return new Date(value);
a = reMsAjax.exec(value);
if (a) {
var b = a[1].split(/[-+,.]/);
return new Date(b[0] ? +b[0] : 0 - +b[1]);
}
}
return value;
};
}
var date = JSON.parse(json,JSON.dateParser);
console.log(date);

jQuery dataTables editor plugin DateTime format issue

I'm using EF6 + MVC for a site. The dataTables editor is used for an UI. One table has a field 'StartDate'. It is a datetime type in the SQL Server.
It works fine until when I try to edit the 'StartDate' value. From the browser debug, I can see that the JSON send from backend to UI is in the timestamp format, i.e. /Date(1541923200000)/ .
In the dataTables, I convert this to the correct local datetime format, so it shows correctly.
However, I could not figure out how to do this in Editor plugin. It always shows the /Date(1541923200000)/ .
The code I use is:
editorAdvertisement = new $.fn.dataTable.Editor({
ajax: '/APN/GetAdvertisementData',
table: "#tblAdvertisements",
fields: [{
label: "StartDate",
name: "AdvStartDate"
, type: "datetime"
, format: 'MM\/DD\/YYYY h:mm a'
}, {
label: "Deadline",
name: "AdvDeadline"
, type: "datetime"
}, {
label: "TitleOfAdv",
name: "TitleOfAdv"
}, {
label: "ListPrice",
name: "ListPrice"
}
]
});
var tbl = $('#tblAdvertisements').DataTable({
pageLength: 10,
dom: '<"html5buttons"B>lTfgitp',
ajax: '/APN/GetAdvertisementData'
,
columns: [
{
data: "AdvStartDate", name: "AdvStartDate"
, type: "datetime"
, render: function (value) {
var r = convertDate(value);
return r;
}
, "autoWidth": true
},
{
data: "AdvDeadline", name: "AdvDeadline"
, type: "datetime"
, render: function (value) {
var r = convertDate(value);
return r;
}
, "autoWidth": true
},
{ data: "TitleOfAdv", name: "TitleOfAdv", "autoWidth": true },
{
data: "ListPrice", name: "ListPrice", "autoWidth": true
, render: $.fn.dataTable.render.number(',', '.', 0, '$')
}
],
order: [1, 'asc'],
select: {
style: 'os',
selector: 'td:first-child'
},
buttons: [
{ extend: "create", editor: editorAdvertisement }
, { extend: "edit", editor: editorAdvertisement }
, { extend: "remove", editor: editorAdvertisement }
]
, select: true
, searching: false
, paging: false
});
In the controller
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult GetAdvertisementData()
{
var request = HttpContext.Request.Form;
var settings = Properties.Settings.Default;
using (var db = new Database(settings.DbType, settings.DbConnection))
{
var response = new Editor(db, "Advertising", new[] { "AdvertisingID" })
.TryCatch(false)
.Model<Advertising2>()
.Field(new Field("AdvStartDate")
.Validator(Validation.DateFormat(
"MM/dd/yyyy",
new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
))
.GetFormatter(Format.DateTime("yyyy-MM-dd HH:mm:ss", "MM/dd/yyyy"))
.SetFormatter(Format.DateTime("MM/dd/yyyy", "yyyy-MM-dd HH:mm:ss"))
)
.Field(new Field("AdvDeadline")
.Validator(Validation.DateFormat(
"MM/dd/yyyy",
new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
))
.GetFormatter(Format.DateSqlToFormat("MM/dd/yyyy"))
.SetFormatter(Format.DateFormatToSql("MM/dd/yyyy"))
)
.Field(new Field("TitleOfAdv"))
.Field(new Field("ListPrice"))
.Process(request)
.Data();
return Json(response, JsonRequestBehavior.AllowGet);
}
}
I could not figure it out after a long search. Anyone had the same issue? Any solution?
Check Out moment.js (https://momentjs.com), download moment-with-locales.js and add it to your ScriptBundle in BundleConfig.cs.
Then in your datatable's javascript code you can render the column in proper date/time format as follows. Note: my locale is 'pt' (Portugal). The date column is rendered as dd/mm/yyyy hh:mm (once again, see the formatting options in https://momentjs.com).
"columns": [
{ "data": "OriginName" },
{ "data": "SmsID" },
{ "data": "DestinationNumber" },
{
"data": "SMSDeliveryDate",
"render": function (data) {
var re = /-?\d+/;
var m = re.exec(data);
var d = new Date(parseInt(m[0]));
moment.locale('pt');
var m = moment(d).format('L LTS');
return m;
}
},
{ "data": "SmsStateDesc" }
],
Hope this info can be useful. I too was stuck with this for a few hours...
José
I had the same problem and eventually found the answer on the Editor forum.
If you look with fiddler (a great tool for seeing what happens) you
see the JSON has this format you get. If you look in the code in
visual studio express and capture what you got before passing it to
JSON you see something like "{12/12/2012 12:12}". So actually the
cause is the JSON.
Refactoring to just the essentials in your first column it should read like this.
This approach solved my problem without any problem. This version is designed to render null dates as blanks, otherwise format as directed. (Update: refactored the answer again, seeing that the next morning the formatted codes were not behaving as expected.)
{
data: "AdvStartDate",
render: function (data, type, full) {
if (data != null) {
var dtStart = new Date(parseInt(data.substr(6)));
return dtStart.toLocaleDateString();
} else {
return "";
}
}

Return list of datetimes to drop down using Ajax

I have a drop down list that I need to fill with datetime values passed from an ajax call. The values that populate look like this: "/date1234847269/" and not actual dates. I just need the dates to be passed into the drop down list. I do not need the time stamps that are also in the datetime value that is returned from the controller.
I'm not sure if jQuery has issues with handling c# datetime values and not strings. Any help would be appreciated. Thanks
My View:
<select id="ddlDate" class="form-control bold">
<option value='0'>--Select Date--</option>
</select>
My Ajax Call:
function loadDateDDL(historicalIsChecked, monthlyIsChecked) {
$.ajax({
type: 'POST',
url: '#Url.Action("GetGroupReportDates")',
dataType: 'json',
data: { isMonthly: monthlyIsChecked },
success: function (returnData) {
convertDate(returnData);
$("#ddlDate").empty();
$("#ddlDate").append("<option value='0'>--Select Date--</option>");
$.each(returnData, function (value, key) {
$("#ddlDate").append($("<option></option>")
.attr("value", value).text(key));
});
//alert(returnData);
},
error: function (ex) {
alert('Failed to retrieve dates.' + ex);
}
});
}
function convertDate(returnData)
{
var date = new Date(returnData);
return date;
}
My Controller:
public JsonResult GetGroupReportDates ( Boolean isMonthly )
{
List<DateTime> reportDates = RealmsModel.RealmsAuditDataInterface ( ).GetGroupQueryRptDates ( isMonthly );
return new JsonResult ( )
{
Data = reportDates,
MaxJsonLength = Int32.MaxValue
};
}
Update 1/21/2016:
I am now passing my json data "returnData" to the javascript function below and converting it based on another stack post: How do I format a Microsoft JSON date?
function convertDate(returnData)
{
var date = new Date(returnData);
return date;
}
This now gives me the error "date = Invalid Date {}, returnData = ["/Date(1451628000000)/"]". I feel like I'm getting close. Any help is appreciated.
I resolved this with the following:
function convertDate(returnData)
{
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(returnData);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
The format you're seeing is the old "microsoft" way of formatting dates. There are 2 ways to get around it.
One way would be to use the JSON.Net serialiser instead of the built in JavaScriptSerializer, as it (since version 4.5) formats dates so that they can be automatically parsed.
Another (quicker) way would simply be to extract the numbers from the date in it's current format as pass them to a new javascript Date object.
function toDate(value) {
return new Date(parseInt(/Date\(([^)]+)\)/.exec(value)[1], 10));
}

How can I get the selected time from my timepicker and assign it to a TextBox value?

I am trying to get the selected time from my timepicker then assign it as the value in the #Html.TextBox() value attritibute. I’ve tried using this line of code: #(timeValue) = timepicker('getTime')… but it doesn’t store a value in the timeValue variable. Then I tried timeValue = timepicker('getTime') and get an error message about datepicker not being defined. The code below works fine except for the part where I need to get the selected value from my timepicker.
How can I get the selected time from my timepicker and assign it to a TextBox value?
Thanks for any help with this one.
string date = "date" + course.Index.ToString();
string time = "time" + course.Index.ToString();
string timeValue = "";
<script type="text/javascript">
$(function () {
$('input[name= #(date) ]').datepicker();
$('input[name=#(time)]').timepicker({});
#(timeValue) = timepicker('getTime');
});
</script>
string day = DateTime.Now.ToShortDateString();
#Html.TextBox(name: time, value: timeValue, htmlAttributes: new { id = time, #class = "TextBoxCss" })
So I kept the code very much like my original post....
string date = "date" + course.Index.ToString();
string time = "time" + course.Index.ToString();
<script type="text/javascript">
$(function () {
$('input[name= #(date) ]').datepicker();
$('input[name=#(time)]').timepicker({});
});
</script>
string day = DateTime.Now.ToShortDateString();
#Html.TextBox(name: time, value: "Set Time", htmlAttributes: new { id = time, #class = "TextBoxCss" })
#Html.TextBox(name: date, value: day, htmlAttributes: new { id = date, #class = "TextBoxCss" })
Then in my controller I'm doing this and I can create a loop to iterate through all texboxes in the list:
[HttpPost]
public ActionResult Edit(int id, FormCollection formCollection)
{
String theTimes = Convert.ToString(formCollection["time0"]);
}
You can't assign javascript to razor variable. Instead use jquery to assign the value.
But first of all, i think you are not using the #Html.TextBox right.
Try,
#Html.TextBox("time", null, new {id = "time", #class = "TextBoxCss"})
Then jquery,
var timeValue = timepicker('getTime');
$("#time").val(timeValue);
Edited:
Use jquery, ajax form serialize. E.g.
$("#sendTimeButton").on("click", function () { // or use on form submit
$.ajax({
type: "POST", // or GET
url: "#Url.Action("Edit", "ControllerName")",
data: $("#myForm").serialize(), //you can use json also JSON.Stringtify
cache: false,
success: function () {
},
error: function () {
console.log("error");
}
});
});
You can also use an array:
var timeArray = new Array();
$(".TextBoxCss").each(function(){
timeArray.push($(this).val()) // loop through all text boxes with class "TextBoxCss"
});
Then the data part is as such:
data: {times: timeArray}, // "times" refer to the argument in your controller
Then in your controller:
public ActionResult Edit(int id, string[] times)

return formatted date from WebMethod to JSON

I have a WebMethod that returns at date {"d":["/Date(1390411800000)/"]}:
[WebMethod]
public static object getBreadCrumbDate(int projectID, int statusID)
{
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var thisId = myEntities.tbBreadCrumbs.Where(x => x.ProjectID == projectID && x.StatusID == statusID).Max(x => x.BreadCrumbID);
var columns = myEntities.tbBreadCrumbs.Where(x => x.BreadCrumbID == thisId)
.Select(x => x.CreateDateTime).ToList();
return columns;
}
}
and I want to format it "mmm dd, yy" (Jan 22, 14) and return it to the calling AJAX but not sure the best way. Here's my AJAX:
function getBreadCrumbDate(projectID, statusID) {
$.ajax({
url: "view-requests.aspx/getBreadCrumbDate", // Current Page, Method
data: JSON.stringify({
projectID: projectID,
statusID: statusID
}), // parameter map as JSON
type: "POST", // data has to be POSTed
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 10000, // AJAX timeout
success: function (result) {
$("#divApprovedStatus").html(result.d[0]);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
}
Right now it prints out /Date(1390411800000)/ but want it formatted. Is it best to do in the jQuery after the success or in the C# when I return it? Whichever way, I'm not sure how to do it and could use some pointers.
Thanks!
It shows some red lines... do you want me to tell you what they say?
I'd say it's easiest to just do it in C# using ToString([time format]) with the proper format.
Since you have a DateTime? object, known as a Nullable<DateTime>, to access the DateTime value, you have to use the Value property of DateTime? (The Value property exists on all Nullable Types.
For "Jan 22, 14", the format would be as follows:
These are just some generic examples of the syntax:
// DateTime object
someDateTimeInstance.ToString("MMM d, yy");
// DateTime? object
someNullableDateTimeInstance.Value.ToString("MMM d, yy"); // assumes no nulls
// DateTime? object with null check
String formattedDateTime = (null != someNullableDateTimeInstance
? someNullableDateTimeInstance.Value.ToString("MMM d, yy")
: string.Empty);
Additionally, you're using Entity Framework which translates your LINQ statements into SQL.
Basically you have to pull the data first, and then format it. Even though CreateDateTime IS a Nullable<DateTime> column, that entire expression is converted by Linq-To-Entities to SQL. And, Linq-To-Entities doesn't know how to translate the method call .ToString(string format).
By separating the query from the format call, we avoid this issue. You get the data from the entities, and call .ToList() which will cause EF to load the data into memory. Then, you can work with this new list containing DateTime? objects and use the ToString(string format) method to get the formatted dates.
In your code:
[WebMethod]
public static object getBreadCrumbDate(int projectID, int statusID)
{
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var thisId = myEntities.tbBreadCrumbs.Where(x => x.ProjectID == projectID && x.StatusID == statusID).Max(x => x.BreadCrumbID);
var columns = myEntities.tbBreadCrumbs
.Where(x => x.BreadCrumbID == thisId)
.Select(x => x.CreateDateTime)
.ToList();
var formattedList = columns
.Select(d => null != d
? d.Value.ToString("MMM d, yy")
: string.Empty) // this is just one example to handle null
.ToList();
return formattedList;
}
}
if you can use datepicker then you could define a JavaScript function
getDateFromJson: function(jsonDateString, languageCode) {
return $.datepicker.formatDate($.datepicker.regional[languageCode].dateFormat, new Date(parseInt(jsonDateString.substr(6), 10)));
}
and then you could define a i18n file for the datepicker as
jQuery(function ($) {
$.datepicker.regional['en-us'] = {
closeText: 'Done',
prevText: 'Prev',
nextText: 'Next',
currentText: 'Today',
monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'],
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
weekHeader: 'Wk',
dateFormat: 'mm/dd/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
$.datepicker.setDefaults($.datepicker.regional['en-us']);
});
//German
jQuery(function($){
$.datepicker.regional['de'] = {
closeText: 'schließen',
prevText: '<zurück',
nextText: 'Vor>',
currentText: 'heute',
monthNames: ['Januar','Februar','März','April','Mai','Juni',
'Juli','August','September','Oktober','November','Dezember'],
monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
'Jul','Aug','Sep','Okt','Nov','Dez'],
dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
weekHeader: 'KW',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['de']);
});
So you could define your language and your dateFormat for it.
Now when you need a Date, just call this function
getDateFromJson(result.d[0], 'en-us'); //for USA Date
getDateFromJson(result.d[0], 'de'); //for German Date
Hope this points you in the right direction!

Categories

Resources