how to pass date datatype in mvc3 - asp.net-mvc-3

[HttpPost]
public JsonResult GetSearchedResults(string searchedHotel)
{
var searchingHotels = clsRepository.GetSearchedResults(searchedHotel, );
return json etc etc
}
This is my Controller. Just Like String, I need to pass Date Datatype. I have A field Name in DataBase of Type Date.Now I need to pass this.how to pass a datatype DATE.?
I have a DatePicker is my main page. When i choose A date from Datepicker, that will be saved in a variable in my Jquery file. so I need to pass this variable to controller.i need to check whether selected date and date in DataBase are equal.

Just change the datatype of your action parameter to DateTime. The default modelbinder will try to convert the value of the sent request parameter to a DateTime value.
public JsonResult GetSearchedResults(DateTime myDateParameter)
{
// do whatever you want with your date
}

Make an ajax POST request to your action with the date as a parameter.
Use jQuery to make the request. See the dosc on how you can do it: http://api.jquery.com/jQuery.ajax/

Related

Save DateTime value Posted from AJAX to MVC action

I am posting DateTime value as a String Via AJAX POST to MVC Action for saving this Value.
But at the Time of Saving the Value in MVC Action, I get the error message in My AJAX response as:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value
My AJAX POST is as,
String dateTime="2013-07-25 11:59:22 PM";
$.ajax({
type:'POST',
url:'SaveSchedule',
data:{start:dateTime},
success:function(data){ }
});
and MVC Action as,
[HttpPost]
public ActionResult SaveSchedule(DateTime start)
{
var schedule = new Schedule { StartTime = start};
db.Schedules.Add(schedule);
db.SaveChanges();
var temp = 0;
return Json(temp);
}
While using ajax function, you should be careful as they are the client side function, hence you should decalre string type parameter in your controller, and within the action convert them into the required data type by using the tryparse methods of C#.
after getting date in string parameter you will convert the date in string to datetime datatype by using datetime.tryparse method, then you will never get such errors while using ajax.

Salesforce Apex: Validating date for format and value

I need to validate a date field which is being entered by a user via a visualforce page.
The format my code expects is "yyyy-MM-dd".
What is the best way to handle this in apex. I have done similar stuff in Java before using certain standard classes which are not available in Apex like SimpleDateFormat for example.
Now I can check if the "format" is correct using a regular expression. But I must also prevent users from entering "9999-99-99" which satisfies the format. I am hoping Salesforce has a good built-in solution.
Thanks,
Calvin
You might try what I call control spoofing. I basically create an empty sObject that has a date field like a Task object (or something similarly light weight). On the screen I display the input for the task date which will render the native date field. Doing this you get salesforce to validate the date input from the user, and the user get's the nice calendar popup as well.
Here is a sample of what that would look like in the controller
public class MyController {
public Task DateInput {get;set;}
public MyController() {
DateInput = new Task();
}
public void save() {
Date dInputDate = DateInput.ActivityDate;
//Format Date
DateTime dtValue = DateTime.newInstance(dInputDate.year(), dInputDate.month(), dInputDate.day());
string sFormattedDate = dtValue.format('yyyy-MM-dd');
}
}
Here is what the Page would look like
<apex:page controller="MyController">
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:pageBlockSectionItem>
<apex:outputLabel for="inputDate" value="My Date"/>
<apex:inputField value="{!DateInput.ActivityDate}" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
You notice the formatting that I did in the save method. You can't use format on Date but you can on DateTime so I just convert the Date to a DateTime and then use the format method to format my date.
Guys I managed to solve my problem because it was a little unique anyways.
So I used a regex to validate the format of the date being entered to ensure it is in yyyy-MM-dd format.
The I used Date.valueOf
This built in method always takes a date in the form of yyyy-MM-dd. It throws an exception if that has a bad value like 9999-99-99 etc....I display the exception's message to the user using e.getMessage() to complete my validation of the date fields.

Enum unbinds from the model on ajax call

I am reading an enum value from the db then bind it to the model. When i post the form with ajax, somehow the enum is unbound or the model property in null or zero but it display properly on the view. I have posted code below. Im using entityframework and mvc3
//model code constructor
public CarModel(Car car)
{
State=(CarState)car.State;
//car.State comes in as an int
//etc setting other variables
}
//CarState property
public CarState {get;set;}
//model code
#Html.DisplayFor(m=>m.CarState)
//Controller code()
Save(CarModel car)
{
//I have code that saves the changes
}
The minute i get to "car", CarState has no value.
It's not quite clear how you are passing this value to the controller action. You have only shown some #Html.DisplayFor(m=>m.CarState) but obviously this only displays a label in the view. It doesn't send anything back to the server. If you want to send some value back you will have to use an input field inside the form.
For example:
#Html.EditorFor(m => m.CarState)
or use a HiddenFor field if you don't want the user to edit it.
In any case you need to send that value to the server if you expect the model binder to be able to retrieve it. The model binder is not a magician. He cannot invent values. He binds values to your model from the Request.

RedirectToAction is swapping day and month on date

I have a controller POST action that redirects to a GET method using RedirectToAction.
return RedirectToAction(SomeActionName, new { date = someModel.someUTCDate });
I have implemented a custom model binder which parses dates using the assumed culture and timezone information, so I am intercepting this correctly. The basic steps in my problem:
POST action is called with a date/time string, which is GMT Standard Time if not specified otherwise
The custom model binder parses this date to a DateTime with a Kind of Utc, and this is bound correctly in the correct format to the model
The POST action redirects to GET using RedirectToAction with the date that was bound as UTC time on the model
MVC3 is now trying to bind a DateTime string value with the month and day swapped around
Somewhere between calling RedirectToAction and rebinding the DateTime value for the GET action, a string conversion is taking place, which appears to be swapping the month and the day around.
Is there a simple way of ensuring that the correct string conversion takes place without the overhead of having to manually convert it for each RedirectToAction call? I would really like to know where this route value to string conversion takes place and whether or not I could influence it to do the correct string conversion.
To illustrate what I have a bit better, I have a custom DateTime model binder
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null || string.IsNullOrEmpty(value.AttemptedValue) || value.AttemptedValue == "null")
{
return null;
}
return FormatHelper.ConvertStringFromGMT(value.AttemptedValue);
}
On redirect I am finding that the model binder's value.AttemptedValue is an incorrectly formatted string.
Well, the issue is now resolved. As far as I can tell, when MVC gets the route values for your redirect, the route values are converted to query string parameters using the invariant culture. This is just some magic that happens behind the scenes. My solution to this problem was to override the controller methods RedirectToAction and RedirectToActionPermanent (the overloads that take a RouteValueDictionary). I iterate over the RouteValueDictionary and convert any date types here using the defined culture and timezone information. Fortunately all of my controllers were already inheriting from a custom base controller so the fix was simple to implement.

Passing a DateTime to controller via URL causing error in ASP .NET MVC 3 (culture)

My application is setted with pt-BR culture (Date is dd-mm-yyyy) in web.config:
<globalization enableClientBasedCulture="false" requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="iso-8859-15" responseHeaderEncoding="utf-8" resourceProviderFactoryType="string" enableBestFitResponseEncoding="true" culture="pt-BR" uiCulture="pt-BR" />
All DateTime created on my system is in right format, but I created a controller method like that:
public ActionResult Test(DateTime date)
{
}
Calling that method direct in the browser is passing null when the date is with portuguese-br format, like that:
mysite/Test/?date=19/01/2012 => date = null in my controller
mysite/Test/?date=01/01/2012 => date is fine, but in US format (mm-dd-yyyy)
How can I fix that, to accept my date format?
There's a gotcha with the default model binder that is not easy to know about but once you know it you no longer make the same mistake:
When you use a POST request, the default model binder uses your culture settings to parse the dates.
When you use a GET request, the default model binder uses CultureInfo.InvariantCulture to parse the dates and ignores your current culture settings.
Since you are using a GET request and passing the date as a query string parameter, you should format it using the invariant culture format when sending it in the url. The correct way to format your date as a query string parameter is yyyy-MM-dd.
You may take a look at the following blog post which gets into more details.
As someone who does a lot of work with US companies, I've had a lot of experience with date issues.
My best advice is to choose an unambiguous format when transmitting.
dd-MMM-yyyy
and
yyyy-MM-dd
Are safe bets, and will be successfully parsed by DateTime.Parse(obj).
If changing the date format is not an option, you should look at DateTime.ParseExact, which allows you to specify the exact format string you are after.
One approach would be to accept the date as a string and then manipulate it in the controller to the correct locale/culture.
Got the same problem using an #Html.Action(..) in a view. For this situation it can be solved by putting the DateTime in a model:
public class MyModel
{
public DateTime Value {get;set;}
}
and in the view:
#Html.Action("MyAction", new { myModel })
Note the new { } around the instance of MyModel, this way the DateTime is not converted to a string. This solution only works for Html.Action() and not for Html.ActionLink() or Url.Action() since MVC is doing a myModel.ToString() in the URL.

Resources