Scenario:
I know this is a simple datetime conversion, but i'm new to backend and conversions. So please help: I use mvc with ajax to pass the date from kendocalender to scheduler to save it in database:
Here is my code:
controller.cs
public int insertnote(string model,DateTime kendodate)
{
tblDailyNotes Dnote = new tblDailyNotes();
int noteid = 0;
//note.RealDate=Convert.ToString(
Dnote.Note = model;
Dnote.RealDate = kendodate;
noteid = _scheduler.InsertDailynote(Dnote);
return noteid;
}
index.cshtml
$("#dailynotes").change(function () {
debugger;
alert("Changed");
var dailynotes = $('#dailynotes').val();
var calendar = $("#SchedulerCalendar2").data("kendoCalendar");
var cal = calendar.value(new Date());
alert(cal);
$.ajax({
![enter image description here][1]
type: "POST",
url: window.location.pathname + "Scheduler/insertnote",
data: {model:dailynotes, kendodate: cal }
})
.success(function (result) {
alert("note saved successfully");
});
});
Question:
this is the cal alert
How do I convert this output from kendocalendar to "2013-09-01 13:27:14.480"(yyyy-mm-dd hh-mm-ss.sss) this format using jquery to save it in database through controller function. Please help.
you can convert string to DateTime by DateTime.Parse
take a look at this
I agree with user2675751's solution. However, I would recomend using Datetime.TryParse() as this will not throw an exception and return a bool to indicate success or failure. This point is covered in the link user2675751 has provided. It is generally best not to trust data coming from the client.
Related
I want to update my chart according to user date selection. here i am using chart js. So i want to pass from date and to date value using Ajax to controller so that i can do data filters. But the problem is that the dates are not submitted to controller action.Please guide me where i have missed.
i have tried many links too but is not helping me.
Post datetime to controller
this is also not helping.
Here is my Script
<script>
function SendDates() {
var ListOfDates = [];
ListOfDates.push($("#fromDate").val());
ListOfDates.push($("#endDate").val());
dates = JSON.stringify({ 'ListOfDates': ListOfDates });
alert(dates)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: "/dashboard/sendDates",
data: dates ,
success: function (data) {
if (data.status == "successfull") {
alert("Dates were sent successfully ");
} else {
alert("Dates werenot sent successfully ");
}
},
error: function (error) {
console.log(error);
}
})
}
</script>
and this is controller
[HttpPost]
public JsonResult sendDates(DateTime receivedDates) {
DateTime dates = receivedDates;
Debug.WriteLine(" Date is:"+ dates );
return new JsonResult { Data = new { status = "successfull" }
};
}
when i change the data type DateTime to String in controller i get success message but seeing debug output there there is blank.
[HttpPost]
public JsonResult sendDates(String receivedDates) {
var dates = receivedDates;
Debug.WriteLine(" Date is:"+ dates );
return new JsonResult { Data = new { status = "successfull" } };
}
When I am sending data from ajax to the controller at that time it showing the title error. While when I am check the datetime that also coming right only. It showing the current datetime only. Still showing the same error.
I know that the same questions is already ask but then also their answer is not solving my issue.
Here is my code
This is my ajax code
var currentdate = new Date();
var utc = new Date(currentdate.getTime())
$.ajax({
type: "POST",
url: "/Branch/Save",
data: JSON.stringify({ Branch: txtBranch.val(), Address: txtAddress.val(), ContactName: txtContactName.val(), Contactno: txtContactNo.val(), PinNo: txtPin.val(), RegistrationNo: txtReg.val(), GSTNo: txtGST.val(), EnrollNo: txtEnroll.val(), Description: txtDesc.val(), CreatedDateTime: utc, CreatedUserID: 0, UpdatedUserID: 0, UpdatedDateTime: 1/1/1990 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var row = $("#tblBranch tr:last-child").clone(true);
AppendRow(row, r.BranchID, r.Branch, r.Address, r.ContactName, r.Contactno, r.PinNo, r.RegistrationNo, r.GSTNo, r.EnrollNo, r.Description);
txtBranch.val("");
txtAddress.val("");
txtContactName.val("");
txtContactNo.val("");
txtPin.val("");
txtReg.val("");
txtGST.val("");
txtEnroll.val("");
txtDesc.val("");
},
failure: function () {
alert(txtReg.val());
}
});
});
This is my controller code
[HttpPost]
public JsonResult Save(BranchRegistration branchRegistration)
{
using (BranchContext entities = new BranchContext())
{
entities.branch.Add(branchRegistration);
entities.SaveChanges();
}
return Json(branchRegistration);
}
The conversion of a datetime2 data type to a datetime data type
resulted in an out-of-range value.
You usually get this error when your database column is DateTime (not nullable) and your code is not properly setting the value for those column and trying to save it.
This part of your data object,
UpdatedDateTime: 1/1/1990
will send the payload like
UpdatedDateTime":0.0005025125628140704
Which cannot be converted to a valid DateTime object.
Ideally you should be setting these dates in the server, just before saving
[HttpPost]
public JsonResult Save(BranchRegistration branchRegistration)
{
branchRegistration.CreatedDateTime = DateTime.UtcNow;
branchRegistration.UpdatedDateTime = DateTime.UtcNow;
using (var entities = new BranchContext())
{
entities.branch.Add(branchRegistration);
entities.SaveChanges();
}
return Json(branchRegistration);
}
I have this OData controller that works fine for GET and Patch method. However, there's a custom GET method that I had to create in order for use to load the data from a different server and copy to the new one from where the OData retrieves the data. When the user "Retrieves" new data, it sends the date as a parameter. Since it's a new claim for the date, I couldn't put the date in the $filter, hence the new GET method.
This is what the GET method looks like:
[ODataRoute("Claims({key})")]
[HttpGet]
[EnableQuery(AllowedQueryOptions= System.Web.OData.Query.AllowedQueryOptions.All)]
public HttpResponseMessage ClaimByDate([FromODataUri] int key)
{
System.Diagnostics.Debug.WriteLine(key);
string date = key.ToString();
DateTime claimDate = DateTime.ParseExact(date, "ddMMyyyy", CultureInfo.InvariantCulture);
DateTime today = DateTime.Today;
if (!ClaimsExistForToday(today))
{
GenerateClaimsList(today, claimDate);
return Request.CreateResponse(HttpStatusCode.OK);
}
return Request.CreateResponse(HttpStatusCode.NotModified);
}
Here's the angularjs controller
vm.retrieve = function () {
if (vm.selectedDate !== null) {
var day = vm.selectedDate.getDate();
var date = (day + "" + (vm.selectedDate.getMonth() + 1) + "" + (vm.selectedDate.getFullYear()));
ClaimService.getClaimsByDate(date)
.then(function (response) { if (response) activate(); })
vm.clear();
}
}
Here's the angular function that's sending the get request:
function getClaimsByDate(date) { //Angularjs service
return $http.get("odata/Claims(" + date + ")")
.then(function (data) {
return true;
});
}
First Issue:
The OData GET method have to have "int" for the parameter. I tried with string and DateTime, but when I send the data with 'string' as paramenter, it won't find the controller at all unless the data was sent as integer. And if I send the date as UTC, I get an error as potentially dangerous and won't execute.
Second Issue:
Sending date as int, it will find the controller if date is sent as 30112015 in the format ddMMyyyy, but it won't find 1112015 or 01112015. It seems like it's only recognizing the date greater than 10. Other than this, everything else works fine including the regular GET method with [EnableQuery].
I found this SO answer Web API and OData- Pass Multiple Parameters which helped me out. I ended up creating a function with the key as parameter. Then it was only a matter of calling the function from Angular.
when passing an object which contains a date from C# to AngularJS
the value of the date appears as "/Date(1408482000000)/" and not as a valid date.
my angular code:
$scope.GetLastCompletedAction = function () {
$http.post('Default.aspx/GetLastCompletedAction', {}).success(function (data, status, headers, config) {
$scope.objects = JSON.parse(data.d);
}).error(function (data, status, headers, config) {
$scope.status = status;
console.log(status);
});
}
objects is a list of objects.
every object contains a field named startDate which appears invalid.
thanks,
Nadav
you can use a funcion like this
$scope.formatDate = function (jsonDate)
{
var milli = jsonDate.replace(/\/Date\((-?\d+)\)\//, '$1');
var date = new Date(parseInt(milli));
return date;
}
I had this problem before and it is the Date object in javascript that does not consider that date valid.
If you pass to the Date constructor only the number which is inside /Date(*)/, you will see it will work. It did for me.
Hope I helped :)
I would like to provide a file download operation by using the jQuery AJAX call with some params under MVC
Example
(javascript)
function DoDownload(startDate) {
$.ajax({
url:"controller/GetFile/",
data: {startDate:startDate}
...
});
}
C# Controller Code
public void GetFile(string startDate) {
var results = doQueryWith(startDate);
// Create file based on results
....
// How do I tell the server to make this a file download??
}
I typically would just make my file download a link such as:
<a h r e f="mycontroller/getfile/1"/>Download</a>
but in the case above the date will be dynamic.
If I don't use ajax, what would be a preferred way to pass in the params to the MVC controller using javascript?
Example:
window.location = "mycontroller/GetFile/" + $("#fromDate").val();
assuming the date is 12-25-2012
Would this produce
mycontroller/GetFile/12/25/2012
would MVC treat this as three params?
What I ended up doing is calling my controller from my javascript like:
var url = "/mycontroller/GetFile?startDate=" + $("#mydate").val() + etc...
window.location = url;
mycontroller.cs
public void GetFile(DateTime startDate)
{
}
My original concern was with the date parameters. I didnt want to have to parse it.
Using the ActionLink helper, you can pass multiple params to your controller:
HtmlHelper.ActionLink(
string linkText,
string actionName,
string controllerName,
object routeValues,
object htmlAttributes
)
So in your case:
#Html.ActionLink("Download file", "GetFile", "MyController", new { startDate = "##" }, new { id="mydownloadlink" })
Using jQuery you can change the value of the startDate in the link with the content of your date picker or textbox.
$("#mydownloadlink").attr("href").replace("##", $("#yourdatetexbox").val);
Then, in your controller, just use one of the other answers here, about FileResult.
Hope this help you...
You can use the File method of controller class to return a file back to the browser.
The below sample returns a pdf file.
public ActionResult GetFile(int id)
{
var fileInfo=repositary.GetFileDedetails(id);
var byteArrayOFFile=fileInfo.FileContentAsByteArray();
return File(byteArrayOFFile,"application/pdf","yourFriendlyName.pdf");
}
Assuming repositary.GetFileDedetails method returns the details of the file from the id.
You may also return the file from a physical location(a path) or a stream. Check all the overloads of the File method and use appropriate one.
This has nothing to do with ajax. this is normal GET request over a browser.
Your controller action method should return a FileResult instead of void. And there is no need to do this via AJAX - in fact, you don't want to do this with AJAX. You'll need the browser involved so it knows to provide a download dialog for the user.
See these links:
Handling an ASP.NET MVC FileResult returned in an (jQuery) Ajax call
File download in Asp.Net MVC 2
I hope this helps.
This works for me. Make sure you return a File from your controller action with contentType as "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" and file name as e.g. "List.xlsx" which should be the same as in the AJAX success call. I have used ClosedXML NuGet package to generate the excel file.
public IActionResult GetFile(DateTime startDate)
{
var results = doQueryWith(startDate);
DataTable dt = new DataTable("Grid");
//populate dt here.
//if you result is a data table you can assign it to dt
dt = results;
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
string fileName = "List.xlsx";
using (var workbook = new XLWorkbook())
{
workbook.Worksheets.Add(dt);
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(content, contentType, fileName);
}
}
}
//.cshtml (JQuery AJAX call to the controller action)
$.ajax({
url:"ControllerName/GetFile/",
data: {startDate:startDate}
contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
xhrFields: { responseType: 'blob' },
success: function (data) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = 'List.xlsx';
a.click();
window.URL.revokeObjectURL(url);
}
});