passing to MVC Control parameter from Javascript - c#

In my jQuery code I am calling a controller action and I'm trying to pass in dates from the fullcalendar plugin:
url: ('Home/List/?dateValueStart=' + new Date($('#calendar').fullCalendar('getView').start))
+ '&dateValueEnd=' + new Date($('#calendar').fullCalendar('getView').end),
In my controller I have my method setup like this:
public ActionResult List(String dateValueStart, String dateValueEnd)
When I debug dateValueStart I see this:
Tue Oct 1 00:00:00 MDT 2013
DateTime dateVal = Convert.ToDateTime(dateValueStart);
But when I try to convert this to a date it tells me it is invalid.
String was not recognized as a valid DateTime.
How can I get a date close to 10/1/2013?

Javascript date support isn't the greatest. There are shorter ways to do the following but they don't work in all browsers:
var formatDate = function(d){
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
return curr_month + "/" + curr_date + "/" + curr_year;
}
var startDate = new Date($('#calendar').fullCalendar('getView').start);
var endDate = new Date($('#calendar').fullCalendar('getView').end);
var url = 'Home/List/?dateValueStart=' + formatDate(startDate) + '&dateValueEnd=' +
formatDate(endDate)
Also, check out this

Related

iCal.net - Get Events at current day

I have this scipt where I parse ical using iCal.Net.
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string iCal = client.DownloadString("https://myurl");
DateTime today = DateTime.Today.ToUniversalTime();
var todayEvents = calendar.Events.Where(e => e.Start.AsUtc >= today && e.Start.AsUtc < today.AddDays).OrderByDescending(e => e.Start.AsUtc);
foreach (var evt in todayEvents)
{
console.log("Sum: " + evt.Summary + " Start: " + evt.Start + " End: " + evt.End);
}
My problem are, I only get events that starts and end the specific day (today in this example).
I do not get events like: Starts yesterday end ends tomorrow.
Any clue of how I solve that?

C# Function works on development machine but fails on web

I have this function in my Visual Studio web app and it seems to work just fine when I run the project on the development machine, but when I publish it to the web and go to the page where the function runs, it always runs the catch exception part. Can anyone help? I'm scratching my head here :( Here is the code for the function.
public void printData()
{
try
{
//The path to the Bid Form
string pdfPath = Server.MapPath("PDF/Bid_Form.pdf");
var pdfReader = new PdfReader(pdfPath);
var pdfOutput = new MemoryStream();
var pdfStamper = new PdfStamper(pdfReader, pdfOutput);
CultureInfo ci = new CultureInfo("en-US");
//This code block gets the date
string date = BidDateTextBox.Value;
DateTime dateNow = Convert.ToDateTime(date);
string newDate = dateNow.ToString("MMMM dd, yyyy", ci);
//This gets the values from the hidden fields
decimal airTotal = (Convert.ToDecimal(at.Value) + Convert.ToDecimal(att.Value));
decimal waterTotal = (Convert.ToDecimal(wt.Value) + Convert.ToDecimal(wtt.Value));
decimal preTestAir = String.IsNullOrEmpty(AirPreTestTextBox.Value) ? 0 : decimal.Parse(AirPreTestTextBox.Value);
decimal preTestWater = String.IsNullOrEmpty(WaterPreTestTextBox.Value) ? 0 : decimal.Parse(WaterPreTestTextBox.Value);
decimal preTestCombine = preTestAir + preTestWater;
decimal airTotalAll = (Convert.ToDecimal(at.Value) + Convert.ToDecimal(att.Value) + preTestAir);
decimal waterTotalAll = (Convert.ToDecimal(wt.Value) + Convert.ToDecimal(wtt.Value) + preTestWater);
//This line gets the total of all areas
decimal combineTotal = Convert.ToDecimal(gt.Value);
//This line gets the checked check boxes in the Per Specifications area
string selectedSpecItems = (String.Join(",", CheckBoxList1.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Text)) + ", " + CustomSpecTextBox.Value);
//This line gets the checked check boxes in the Exclusions area
string selectedExItems = (String.Join(",", CheckBoxList2.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Text)) + ", " + CustomExcTextBox.Value);
//This checks if the pre test check box is checked. If so it doesnt include the pretest amounts.
if (PreTestCheckBox.Checked) {
pdfStamper.AcroFields.SetField("PreTestAirBid", "$" + preTestAir);
pdfStamper.AcroFields.SetField("PreTestWaterBid", "$" + preTestWater);
pdfStamper.AcroFields.SetField("PreTestCombineBid", "$" + preTestCombine);
pdfStamper.AcroFields.SetField("PreTestText", "Pre-Test");
pdfStamper.AcroFields.SetField("AirBid", "$" + airTotal);
pdfStamper.AcroFields.SetField("WaterBid", "$" + waterTotal);
pdfStamper.AcroFields.SetField("CombineBid", "$" + combineTotal);
}
else
{
pdfStamper.AcroFields.SetField("PreTestAirBid", "");
pdfStamper.AcroFields.SetField("PreTestWaterBid", "");
pdfStamper.AcroFields.SetField("PreTestCombineBid", "");
pdfStamper.AcroFields.SetField("AirBid", "$" + airTotalAll);
pdfStamper.AcroFields.SetField("WaterBid", "$" + waterTotalAll);
pdfStamper.AcroFields.SetField("CombineBid", "$" + combineTotal);
}
pdfStamper.AcroFields.SetField("Date", "" + newDate);
pdfStamper.AcroFields.SetField("Bid#", "");
pdfStamper.AcroFields.SetField("Location", "" + LocationTextBox.Value);
pdfStamper.AcroFields.SetField("ProjectName", "" + ProjectNameTextBox.Value);
pdfStamper.AcroFields.SetField("Engineer", "" + EngineerTextBox.Value);
pdfStamper.AcroFields.SetField("EngineerPhone", "");
pdfStamper.AcroFields.SetField("EngineerFax", "");
pdfStamper.AcroFields.SetField("Architect", "" + ArchitectTextBox.Value);
pdfStamper.AcroFields.SetField("ArchitectPhone", "");
pdfStamper.AcroFields.SetField("ArchitectFax", "");
pdfStamper.AcroFields.SetField("Specifications", "" + selectedSpecItems);
pdfStamper.AcroFields.SetField("Exclusions", "" + selectedExItems);
pdfStamper.FormFlattening = false;
pdfStamper.Close();
pdfReader.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=NewBid.pdf");
Response.ContentType = "application/pdf";
Response.BinaryWrite(pdfOutput.ToArray());
Response.End();
}
catch (Exception e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorAlert", "alert('An error has occured.');", true);
}
}
Without knowing the exception my guess would be the server does not have appropriate access to the file at the path you are referencing. Try outputting the exception message in the catch block instead of your custom error message. Should help.

How to pass variable in jquery set date

I am trying to execute some JS code using C#:
executor.ExecuteScript("window.document.getElementById('pmtDate').setAttribute('value','08/16/2013');");
Instead of 08/16/2013 I would like to pass variable for Date.
Can anyone please let me know the syntax for this?
var temp_date='08/16/2013';
executor.ExecuteScript("window.document.getElementById('pmtDate').setAttribute('value',tempdate);");
My understanding, you want the date in mm/dd/yyyy format.
To get the current date, use the below code:
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var today = (month<10 ? '0' : '') + month + '/' + (day<10 ? '0' : '') + day + '/' + d.getFullYear();
Now use this with your code.
executor.ExecuteScript("window.document.getElementById('pmtDate').setAttribute('value',"+today+");");
If I get you right:
executor.ExecuteScript("var date = '08/16/2013'; window.document.getElementById('pmtDate').setAttribute('value',date);");
There are two main techniques for doing this. One is string concatenation, the other is string interpolation.
Concatenation
var theDate = "8/16/2013";
var theCommand = "window.document.getElementById('pmtDate').setAttribute('value'," + theDate + ");"
executor.ExecuteScript(theCommand);
Interpolation
var theDate = "8/16/2013";
var theCommand = String.Format("window.document.getElementById('pmtDate').setAttribute('value', {0});", theDate);
executor.ExecuteScript(theCommand);
If you're using Selenium, you can also pass an argument array to the function:
var theDate = "8/16/2013";
var theCommand = "window.document.getElementById('pmtDate').setAttribute('value', arguments[0]);";
executor.ExecuteScript(theCommand, new object[] { theDate });
Try this:
var currentDate = new Date();
window.document.getElementById('pmtDate').setAttribute('value', getDate());
function getDate(){
return currentDate.toString();
}
Fiddle
Updated Answer:
executor.ExecuteScript("function getDate(){return currentDate.toString();}var currentDate = new Date();window.document.getElementById('pmtDate').setAttribute('value', getDate());");

Is there any way to change date time formatting in JSON?

I'm using JSON to send data to client. However, the date fields get transformed into a timespan format like /Date(1363807800000)/.
Is there anyway to get rid of it and let server send DateTime values like 2013/7/21 3:44 PM to client?
Think of this,
var data = "/Date(1363807800000)/";
var date = new Date(parseInt(data.replace("/Date(", "").replace(")/", ""), 10));
var result = date.getFullYear() + "-" + (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " " + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());
Then, use this RegEx to validate it,
/ ^ \ d {4} - \ d { 2} - \e{2} \e{2}:\e{2}:\e{2} $ /
Hope this helps...:)
Here is a solution using Json.NET (you can install it via NuGet):
object testObject = new { Name = "TestName", DateTime = DateTime.Now };
string output = JsonConvert.SerializeObject(testObject, new IsoDateTimeConverter());
Console.Write(output);
Output:
"{\"Name\":\"TestName\",\"DateTime\":\"2013-07-21T15:01:56.2872469+03:00\"}"
In case ISO DateTime format does not work well for you, you can write your own DateTimeConverter to use with SerializeObject function.
I wrote once this, maybe you could add the string to your json ?
var getDate = function() {
var date = new Date();
var prefix = "["
+ date.getDate() + "."
+ (date.getMonth() + 1) + "."
+ date.getFullYear() + " "
+ date.toString().split(" ")[4]
+ "]";
return prefix;
};

Adding week number and week ranges of a year to DropDown List in ASP.NET3.5 using JQUERY

I am learning jQuery. Here I have a requirement i.e I have to add Week number and Week ranges of a year to DropDown List in ASP.NET3.5. And I have to pass selected week range to database. I am using c#.net. This should be done automatically for every year.
How can I do this using JQUERY?
Regards,
JN
try this
function getDateRangeOfWeek(weekNo){
var d1 = new Date();
numOfdaysPastSinceLastMonday = eval(d1.getDay()- 1);
d1.setDate(d1.getDate() - numOfdaysPastSinceLastMonday);
var weekNoToday = d1.getWeek();
var weeksInTheFuture = eval( weekNo - weekNoToday );
d1.setDate(d1.getDate() + eval( 7 * weeksInTheFuture ));
var rangeIsFrom = eval(d1.getMonth()+1) +"/" + d1.getDate() + "/" + d1.getFullYear();
d1.setDate(d1.getDate() + 6);
var rangeIsTo = eval(d1.getMonth()+1) +"/" + d1.getDate() + "/" + d1.getFullYear() ;
return rangeIsFrom + " to "+rangeIsTo;
};
answer is originally from
http://snipplr.com/view/7540/get-date-range-from-week-number-in-year/

Categories

Resources