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.
Related
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
I am working on Visual C# MVC project. I am using EF databse first approach in my model.My project is about developing an appmarket where users can buy apps. I used partial view in home page which will contain details of different apps in different partial views.Like App1 in 1st partial view, App2 in 2nd partial view, so on. For this I used for each loop.
In each partial view there is link called MoreInfo, so when user clicks on that they will go inside MoreInfo page. In database I have fields such as app info, app cost, description etc which will be displayed inside MoreInfo page. All these fields are in one table called Apps table.
When i follow Enumerable.FirstOrDefault approach I am able to retrieve only first record from database. But now my problem is I need to retrieve first record in my first MoreInfo view, second record in second MoreInfo view and so on.
My code for controller is :
public ActionResult MoreInfo()
{
var e = Enumerable.FirstOrDefault(db.AppmarketApps);
return View(e);
}
and in view i used :
#model Market.Models.AppmarketApp
<h3><span class="grey">MARKETPLACE ›</span> #Model.Description</h3>
So here I am getting first record description for all MoreInfo views which I don't want.
Thanks in advance.
Expanding on my comment you should use the ID of the application and then pass that into MoreInfo so something like this:
public ActionResult MoreInfo(int id)
{
var e = db.AppmarketApps.Where(x => x.ID == id).FirstOrDefault();
return View(e);
}
Pass the Id of the app of interest in the link to MoreInfo and query your data based on that id.
Finally after playing with my code I got to know solution for this.
Before I had two controllers called HomeController and MoreInfoController. But since MoreInfo link was in Homepage itself, I removed MoreInfo controller and added code to HomeControoler itself. Here is the code which i add :
public ActionResult MoreInfo(short id)
{
var e = db.AppmarketApps.Where(x => x.ID == id).FirstOrDefault();
return View(e);
}
Here I am passing id as parameter and capital 'ID' is my primary key.Since i wanted to display only one record per view, i used FirstOrDefault method.
After this in my view I changed code like this :
#Html.ActionLink("MoreInfo", "MoreInfo", new { id = item.ID }, new { #class = "greyButton" })
Here first parameter "MoreInfo" is LinkName and Second parameter "MoreInfo" is link. As you can see when user clicks on MoreInfo link, id will be passed to that link by using
new { id = item.ID }.
class is used for style purpose.
To be clear what above code does is, it will pass id to MoreInfo link and will display data present in AppmarketApps table.
Finally i used #Model.Name in my view if i wanted to display 'Name' and I used #Model.Description if i wanted to display 'Description' and so on.
Thanks to all who helped me in this.
On my view I am using a list as my model and each list item is of type model, so it looks like this:
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
and I am trying to loop through this list and add a specific property to a DropDownListFor:
#for (int i = 0; i < Model.Count(); i++)
{
Html.DropDownListFor(model => model.ElementAt(i).module, new SelectList(Model, Model.ElementAt(i).module));
}
But when I do this it doesn't render a dropdownmenu on my page.
Can someone help?
You can't render a dropdown list for a model because there is no way of representing the model in its entirety in a dropdown. What is ASP.NET supposed to render?
What you can do if you would like to select a model from a list is to run a LINQ Select query on the list, whereby you create an IEnumerable<SelectListItem> like this:
var selectList = Model
.Select(x => new SelectListItem
{
Name = x.module_name,
Value = x.module
});
I have tried to take the values from the screenshot that you posted. Apologies if I made an error. You get the idea...
What this code does is loop through the collection of your object type (Model.Select) and returns a collection of SelectListItem. If you are unfamiliar with LINQ you need to think of Select as a transformative function. It takes a collection, and for each element transforms it into something else and returns the result. Here, it takes each element of the Model collection and creates a SelectListItem. It then returns an IEnumerable<SelectListItem>.
To render the list on the page you do the following:
#Html.DropDownListFor(Model.MyValue, selectList)
...where Model.MyValue is the variable which receives the selected value (assuming that the value, model is a string, which it appears to be).
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
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.