Subtracting 2 Dates from Database - c#

I have 2 Dates which I pull out from a database. One being a Start Time and One being an End Time. I am wanting to find the difference between the 2 dates and then display the time taken between the 2 on the same page.
I have seen this code on other answers but I am new to this so not sure where to place it and then display it on a page.
var ExecutionSeconds = execution.End.Subtract(execution.Start).TotalSeconds;
Any help would be greatly appreciated.
Thanks

The first Thing is that you Need a DbContext in your conroller to get execution from you database. Then you can execute your code line to determine the time span in seconds.
The second part is to give this value to your view. For example by passing it to the View-method as the model:
//fetch your data and calculate ExecutionSeconds...
return View(ExecutionSeconds);
}
Inside the View you can access your model by declaring the #model element and accessing the Model property:
#model Int32
#* other HTML code you need *#
<span>The timespan is #Model seconds long</span>

One way is to have read only property on the model
public int ExecutionDiff{
get{
return this.End.Subtract(this.execution.Start).TotalSeconds;
}
}
Or put calculated value to the ViewData or ViewBag and take value from there

one way to have the below function which gives you the difference in days.If you want to check difference in js change the function appropiately.
public int DayDiffrenceInt(DateTime date1, DateTime date2)
{
var a = (date2.Date - date1.Date).Days;
return a;
}

If your query contains StartDate and EndDate, Then you can subtract each row this way:
var dateQuery = dateTimeQuery.Select(p => p.StartDateTime - p.EndDateTime).ToList();
Then you can assign that query in a ViewBag:
ViewBag.DateTimes = dateQuery;
So inside your view you can easily show it:
foreach (var dateTime in ViewBag.DateTimes)
{
<li>#dateTime.TotalSeconds</li>
}

I managed to solve this using ViewBag.
Controller
ViewBag.ExecutionSeconds = (execution.End - execution.Start).TotalSeconds;
View
#ViewBag.ExecutionSeconds

Related

How can I get the current page number in GridMvc?

I am developing MVC application in which I have used GridMvc,
Now I am trying to use skip and take on index view. But here I want to get the current page number in the view, which means I would need to pass it from the view (where pagination is handled) to the controller (where I need it). But how can I get the page number in the controller, or how can I pass a variable back up the chain?
Here is the code for my index view, where the pagination is handled
#model IEnumerable<Epay.ViewModel.PurchaseOrderVM>
#using GridMvc.Html
#Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.PoNo).Titled("PO No").SetWidth(200);
columns.Add(c => c.PoDate).Format("{0:dd-MMM-yy}").Titled("PO Date").SetWidth(150);
columns.Add(c => c.CompanyName).Titled("Company").SetWidth(500);
}).WithPaging(10).Sortable(true)
And here is the code for the controller, where I am trying to get the page number
public ActionResult Index()
{
PurchaseOrderService POService = new PurchaseOrderService();
var POList = POService.GetAll();
return View(POList);
}
As per the source code, you should be able to get the current page number using the query string parameter "grid-page". But this parameter can be modified while constructing the grid. You can check the implementation for the property "CurrentPage". Link for the source code is below.
http://gridmvc.codeplex.com/SourceControl/latest#GridMvc/GridMvc/Pagination/GridPager.cs
If you return an IEnumerable or IQueryable as the model then GridMVC should do the paging for you. You do not have to manually do it.

Kendo UI: Get MultiSelect selected values as a comma separated string

I'd appreciate if someone could help with my issue.
I have an entity with field PAYMENT_CURRENCIES of string type, that should store comma separated values, i.e. "USD,EUR,AED" (or any other separation char).
In my View:
#Html.Kendo().MultiSelectFor(model => model.Contract.PAYMENT_CURRENCIES).BindTo(context.Currencies).DataTextField("CODE").DataValueField("CODE").Placeholder("Add currency...")
The problem is when I submit the form i receive only first selected value in the Controller.
I would not like to change the datatype of the field for IEnumerable.
Is there a way to receive all selected values as a string with some separator?
Thanks a lot
I don't think that you can automatically convert your multi select input value(s) to a single string.
So what you can do is:
Use a viewModel (ContractViewModel) which contains a List
Or use javascript to "convert" your input value(s) to a single string separated with any separator you want
Add an array-property to your model:
public string[] PAYMENT_CURRENCIES_LIST
{
get
{
return PAYMENT_CURRENCIES?.Split(',');
}
set
{
PAYMENT_CURRENCIES = string.Join(",", value);
}
}
Then use this property in your view:
#Html.Kendo().MultiSelectFor(model => model.Contract.PAYMENT_CURRENCIES)...
So the array-property maps to the Kendo-Multiselect and translates the values to/from the original field.
I had the same requirement as yours, & couldn't find a decent solution, That's how I solved it:
Create a new Property in your ViewModel public List<string> SelectedCurrencies { get; set; }
Configure your MultiSelect Kendo helper to bind to the newly created property #Html.Kendo().MultiSelectFor(model => model.SelectedCurrencies)
.BindTo(context.Currencies)
.DataTextField("CODE")
.DataValueField("CODE")
.Placeholder("Add currency...")
To Save: Now when you hit your action method, just set your comma separated field PAYMENT_CURRENCIES = string.Join(",", viewModel.SelectedCurrrencies);
To Read: SelectedCurrencies = PAYMENT_CURRENCIES.Split(',').ToList();

.NET MVC 4 - Best practices for keeping state of a list of selected objects

This should be an easy one, but without ViewState, I'm clueless here (I've been babied with WebForms for too long, I know!).
My scenario:
View
#foreach (var product in Model.Products)
{
<tr>
<td>#Html.ActionLink("Compare", "Compare", new { id = product.ProductId })</td>
</tr>
}
Controller
public ActionResult Compare(int id = 0)
{
var product = SelectProduct(id); // selects the product from a list of cached products.
if (product != null)
{
// _productDetails is a Model specifically for my View.
_productDetails.ComparedProducts.Add(product);
}
return View("Index", _productDetails);
}
Obviously, when you click on "Compare" for each item, it'll add to the the ComparedProducts list. But, with there being no ViewState, this will get cleared on every page refresh and lose the last product. I want products to be kept in this ComparedProducts list, but how?
I'm guessing they need to be appended to the querystring, so /Carousel/Compare/?id=2122,1221,1331,1333 etc. If so, how is this possible?
Thanks in advance.
Updated
If I did want to go the query string route, how do I do this?
I've tried:
<td>#Html.ActionLink("Compare", "Compare", new { id = product.ProductId, compared = Model.ComparedProducts.Select(a => a.ProductId) })</td>
But that brings out:
compared=System.Linq.Enumerable%2BWhereSelectListIterator`2[Product%2CSystem.Int32]
Which I'd expect really. I guess I'd make yet a further ViewModel property and simply store the Compared Id's in there to not have much business logic within my View?
+1 for your relationship with webforms :)
I think from now on, you can start to keep state in the other ways you already know from webforms like Session State: http://msdn.microsoft.com/en-us/library/ms178581(v=vs.100).aspx
You are also right on the querystring, after all, if you want to keep things simple, is better to use the simplest methods , for instance:
<url>?reference=123&compare=456
EXAMPLE
you need the first action as HttpGet and now this one as httpPOST
[HttpPost]
public ActionResult Compare(myModel model)
{
var product = SelectProduct(model.reference); // selects the product from a list of cached products.
if (product != null)
{
// _productDetails is a Model specifically for my View.
// you can always update the model you got in the first place and send it back
model.ComparedProducts.Add(product); //
}
return View("Index", model);
Your view should react according to empty properties to display

Getting an ID of a value from dropdown list

Hey,
I Have three IQueryable lists which i concat together into one list to be displayed in the dropdown box. But now I want to get the id of what the user selected since there are 3 lists to choose from. Thanks
Example:
IQueryable<Store> stores= _storeRepository.FindAll().OrderBy(c => c.Description);
var storeList = stores.ToSelectList("StoreId", "Description", viewModel.StoreId.ToString());
IQueryable<Product> products = _productRepository.FindAll().OrderBy(j => j.Name);
var productList = products.ToSelectList("ProductId", "Name", viewModel.ProductId.ToString());
var viewList = storeList.Concat(productList).ToList();
viewModel.Lookups = viewList; //display in dropdown
if you question was i have 3 lists and the user choose one how can i know which one he chosen
Answer :
you give all three the same name and the value will change depend on which one the user have chosen
if your question was i want to send the id value with the selected list
Answer :
the server doesn't have any info about your html attributes
just the name attribute which maps to the action method parameter name and the value which maps to the parameter value , you can't know the id value and other attributes in the server
Example :
<input type="text" name="Title" id="SomeValue"/>
Will Map To :
public ActionResult Index(string Title)
the server will not recive id="SomeValue"
Solution :
What you can do is place a hidden field under every item with the value you want
instead of this way, after concatenating do this
viewdata["viewList"] = storeList.Concat(productList).ToList();
and view display items in dropdown like this
<%= Html.DropDownList("viewlist_id", (List<SelectListItem>)ViewData["viewlist"])%>
now use a submit button (if want to post the data to same action else use actionlink with routvalues if redirecting to different action,I am using here submit button)
<input type="submit" name="submit" value="submit" />
and in your action you can retrieve the posted data
var dropdown_id = Request.Form["viewlist_id"];
this way you will get the id of selected drop down. thanks
So i figured out how to have the values of different lists combined into one dropdown list will still being able to access its actual value or ID without concat or union- the code is a lot if anyone is interested i will go ahead and take the time to properly post it. Other than that, thank you everyone for offer your advise and help. Thanks
So this is how i went about my problem. In my Controller File - in my Get method after the button click this is what i did:
resultSummaryViewModel.Value = value;
resultSummaryViewModel.ReportFrame = new FramedViewModel();
if(value !="")
{
string viewValue = value.Substring(0, value.IndexOf("|"));
string viewType = value.Substring(value.IndexOf("|") + 1);
resultSummaryViewModel.ReportFrame.SourceURL =
WebPathHelper.MapUrlFromRoot(
string.Format(
"Reporting/ResultSummary.aspx?beginDate={0}&endDate={1}&Id={2}&viewType={3}",
resultSummaryViewModel.BeginDate, resultSummaryViewModel.EndDate, viewValue,
viewType));
}
var viewData = new Dictionary<string, string>();
viewData.Add("Schools", "|allschools");
viewData.Add("Classes", "|allclasses");
This is also connected to my display page aspx.cs which contains the actual lists i use to populate.

Why does this render as a list of "System.Web.Mvc.SelectListItem"s?

I'm trying to populate a DropDownList with values pulled from a property, and my end result right now is a list of nothing but "System.Web.Mvc.SelectListItem"s. I'm sure there's some minor step I'm omitting here, but for the life of me I can't figure out what it is.
The property GET generating the list:
public IEnumerable<SelectListItem> AllFoo {
get {
var foo = from g in Bar
orderby g.name
select new SelectListItem {
Value = g.fooid.ToString(),
Text = g.name
};
return foo.AsEnumerable();
}
}
The controller code:
public ActionResult Edit(string id) {
// n/a code
ViewData["fooList"] = new SelectList(g.AllFoo, g.fooid);
return View(g);
}
The view code:
<%= Html.DropDownListFor(model => model.fooid, ViewData["fooList"] as SelectList) %>
The problem here is that you shoudn't fill a SelectList with an IEnumerable<SelectListItem>. Use either SelectList or an IEnumerable<SelectListItem>, but not both. For more details, have a look at this question: Asp.Net MVC 2 Dropdown Displaying System.Web.MVC.SelectListItem
I ran into the same problem. You should render your List in the view like
#Html.DropDownListFor(model => model.fooid, new
SelectList(ViewData["fooList"],"Text","Value", Model.DefaultValue))
This is based on c# with razor view
EDIT: This question is very similar to one that was already asked:
ASP.NET MVC 2 - Html.DropDownListFor confusion with ViewModel
Otherwise, you might find this article helpful:
http://www.nickriggs.com/posts/rendering-and-binding-drop-down-lists-using-asp-net-mvc-2-editorfor/
It uses EditorFor, but the same can be done for DisplayFor.

Categories

Resources