How to get the data in MM/dd/yyyy format in Linq - asp.net-mvc-3

Login authentication on my website is based on three parameters of which one is date of birth. A DatePicker is provided to the user to select the Date. The format in which the date is saved in Database is MM/dd/yyyy.
When is check for the authentication the Linq query is not returning any result as the record in Database is in MM/dd/yyyy and the value passed from the view to the controller is in dd/mm/yyyy.Hence im not getting any output.
Below is my code of what I'm doing in controller.
[HttpPost]
public ActionResult Login(LoginTable log)
{
var login = from a in db.LoginTables
where a.DOB== log.DOB
select a;
}
Also I have tried
var login = from a in db.LoginTables
where a.DOB== log.DOB.toString("MM/dd/yyyy")
select a;
but its giving error (No Overload method 'ToString()' takes 1 argument)
What can i do?

The reason this is failing is because the LINQ is translated into SQL syntax and there is no equivalent of ToString in SQL.
Given that log is a parameter to your method why not simply have:
[HttpPost]
public ActionResult Login(LoginTable log)
{
string DOBString = log.DOB.ToString("MM/dd/yyyy");
var login = from a in db.LoginTables
where a.DOB == DOBString
select a;
}

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.

how to pass date datatype in mvc3

[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/

How to use the array of values in the WHERE clause of my query

I am using asp.net mvc3. I want to pass an array from view to the controller using parameterMap as shown below. In my view:
parameterMap:
function (data, options) {
if (options === "read") {
sessionStorage.setItem("value","array");
val = sessionStorage.getItem("value"); // contains array
return { model: JSON.stringify(val) }; //passing array to controller
}
}
In controller:
public ActionResult SearchDetails( string model)
{
var query = (from ......).where();//want to compare array values in controller
}
but I am not able to retrieve those values in the controller. How can I retrieve these array of values in my controller without using looping statements?
My array contains only integer values (ids), while debugging the when I put cursor at the parameter of action method the values are coming in ""[{\"id\":1},{\"id\":2}]"" format. How can I use this array of values in my WHERE clause of my query?
if you are bound and determined to stick with the string input, I would think a call to Split would work. However, it would be much easier if you changed from bringing it in as a string to just bringing in the model. Have you tried something like:
public ActionResult SearchDetails( model model)
{
var query = (from ......).where();//want to compare array values in controller
}
are you trying to do something equivalent to a SQL IN? If that is the case then use .Contains in your query. For example:
public ActionResult SearchDetails(model model)
{
var query = from d in context.data
where model.Contains(d.id)
select d;
}

Displaying records from database which are equal to logged on user

I have created an MVC3 application which needs to show user specific data. The problem I am having is trying to display records which are equal to #user.Identity.Name.
The following Linq to SQL has been used to try to accomplish this:
public ActionResult Index()
{
using (var db = new mydatEntities())
{
var details = from t in db.testadtas
where t.UserID == Viewbag.UsersRecord
select t;
return View();
}
}
(Update)
New to c# and Linq and finding it hard to write a query which will only display the logged on users records.
I have used the code below
MembershipUser currentUser = Membership.GetUser (User.Identity.Name, true /* userIsOnline */);
Viewbag.UsersRecord = currentUser.ProviderUserKey;
I have then input the Viewbag.UserRecord into a textbox which updates a database field with the UserID in a table I have created.
I now want to write a linq query to say if UserID = Viewbag.UserRecord then show record with the UserID only
Is this a correct method to use for showing logged on user records?
or is there any other way which I can implement this in MVC3?
Just use HttpContext.User.Identity.Name

MVC ddl value after postback

I have a ddl which is populated with hours of day 01-23. This is on a form which is used to book an item of equipment. The hour is populated to a db field. The issue is this, when the booking form is opened to alter the time the ddl shows the hour that was booked, when changed though and the form is submitted the value passed on post is the initial value from db not the new selected hour.
this is the basic pieces of code. any idea why the newly selected ddl value is not passed to the model??
View
<%= Html.DropDownList("ddl_Hour", Model.ddlHour,
new { #class = "DropDown", style = "width: 40px” })%>
Model
private string _ddlHourSelectedValue = "0";
public SelectList ddlHour
{
get
{
return (new System.Web.Mvc.SelectList(_ddlHour, "intValue", "Text", Convert.ToInt32(_ddlHourSelectedValue)));
}
}
public string ddlHourSelectedValue
{
get
{
return _ddlHourSelectedValue;
}
set
{
_ddlHourSelectedValue = value;
}
}
param[6] = new SqlParameter("#Timeslot", ddlHourSelectedValue);
The field in your view is called "ddl_Hour" However is there a variable in your Model with the same name? Otherwise the MVC framework will not automatically populate the value in the model.
Two ways you could go about this.
1
In your controller methods that accepts a post, you can add the parameter: FormCollection fc to the method. This key value pair collection will allow you to fetch results from fields in the post data like so:
string selectedValue = fc["ddl_Hour"];
2
Or you can modify your model to include a variable with the same name as the drop down list so that it is automatically populated for you.
public string ddl_Hour { get; set; }
You should then be able to access the result of the drop down list selection on post from that variable.

Resources