I want to run a loop in Asp.net MVC using two dates and want to fetch all data from database that exist between these two dates, Please help me.
Asked
Active
Viewed 606 times
0
-
1Why you can't fetch them in SQL query to your database with use of BETWEEN keyword? – Sergey Litvinov Jan 03 '14 at 11:20
-
I am using Razor coding inside view in MVC, so that i am not using between keyword. – Arvind Jan 03 '14 at 11:30
-
Sergey Litvinov is right , try to use sql query to fetch values from database. created a sample sqlfiddle here. http://sqlfiddle.com/#!3/7e887/6/0 – Bumble Jan 03 '14 at 11:37
1 Answers
3
If you need to make it via Razor, then you can use such code:
@for (DateTime item = model.BeginDate; item <= model.EndDate; item = item.AddDays(1))
{
<div>Date is @item</div>
}
But if you need to fetch data from DB, it will be better to include it in the SQL query that fetch this data with BETWEEN keyword. Here is a sample:
SELECT * FROM SomeSource WHERE DateColumn BETWEEN @BeginDate AND @endDate
UPDATE1 I didn't use nHibernate before, but seems there is an answer on SO about it - Querying with nHibernate where todays date is between publishDate and Expiry date
Basically you can write such code:
DateTime beginDate, endDate;
// init datetime values
return _session.CreateCriteria<Message>()
.Add(
Restrictions.Le("BeginDate", beginDate)
& Restrictions.Ge("EndDate", endDate))
.List<SomeResultType>();

Community
- 1
- 1

Sergey Litvinov
- 7,408
- 5
- 46
- 67
-
Can you please help me in writing sql code inside view, i am using nhibernate , between clause is not working – Arvind Jan 03 '14 at 12:33
-
I didn't use nHibernate, but i found a sample on SO and updated answer – Sergey Litvinov Jan 03 '14 at 12:40