Mr A
Mr A

Reputation: 6768

How to calculate date difference in mvc and hide/show Html.Actionlink according to the difference

I have got the date field in my db , What I want to do is find the date difference betwwen current date and the date of the product created(which is in db) . For instance if the product date is 22/08/2012 and current date is 15/07/2011 therfore the difference is 38 days , After calculating the difference once should check the logic and display the action link according to it ,

The logic is fixed and simple:

If(dateDifference > 5 )
{ show Actionfilter } 
else
{
hide Actionfilter}

Action filter in the view

<p>    <%= Html.ActionLink("Pay by Cheque", "PayByChecque", "Booking", null, new { id = "paycheque", @class ="test"  })%></p>

Any help or suggestion will be appreciated.

I was thinking of doing the calculation in the controller and pass it through view bag to the jquery like:

$('#paycheque').hide();
$('Viewbag.difference').value > 5{

$("#showdiv").show();
else
$("#showdiv").hide();

});

But I am struggling with calculating the difference

Upvotes: 0

Views: 2691

Answers (2)

S&#246;ren
S&#246;ren

Reputation: 133

Calculating difference in days using C#

In the View you can use

<% if(Model.XXX > 5) { %>

   <!-- display --> 
   <p>
     <%= Html.ActionLink("Pay by Cheque", "PayByChecque", "Booking", null, new { id = "paycheque", @class ="test"  })%>
   </p>

<% } %>

Model is defined in the first line of the View-Source. In your Model you define a field, that holds the difference.

Don't let the View calculate it.

Upvotes: 1

Iain Galloway
Iain Galloway

Reputation: 19190

Your view should not be responsible for doing the calculation.

Usually your controller would load a model from the database, and use that model to populate an appropriate ViewModel object (as above) which is responsible for "shaping" the data into the format that your view needs it in.

Try something along the lines of the following:-

MyViewModel.cs:-

public class MyViewModel
{
  public DateTime FirstDate { get; set; }
  public DateTime SecondDate { get; set; }

  public bool SheIsIntoYou
  {
    return SecondDate.Subtract(FirstDate).Days < 5
  }
}

And in your view (which is strongly typed on MyViewModel):-

<% if (Model.SheIsIntoYou) { %>
  <%: Html.ActionLink("Ask out again", "MyController", "MyAction") %>
<% } %>

Upvotes: 3

Related Questions