pagination in ASP.NET MVC without using any external nuget package - asp.net-mvc

Could you please let me know is there any way to do the pagination in ASP.NET MVC without using any external nuget package(Eg : PageList.mvc). Actually I'm looking for a server side solution to do the pagination in MVC itself.
Please help me if some one know the answer.
Thanks
Nishad

You can use WebGrid. It's not a NuGet package, it's part of the System.Web.Helpers namespace and provides pagination functionality out of the box.
1.Model:
public class Product
{
public int ID { get; set; }
public string Description { get; set; }
}
2.View:
#model IEnumerable<MVCTutorial.Models.Product>
#{
Layout = null;
WebGrid grid = new WebGrid(Model, canPage: true, canSort: false, rowsPerPage: 2);
}
#grid.GetHtml(
tableStyle: "table",
columns: grid.Columns(
grid.Column("ID", "ID", format: #<text> #item.ID
</text>, style: "p13"),
grid.Column("Description","Description", format: #<text> #item.Description</text>)))
3.Controller:
public class HomeController : Controller
{
public ActionResult GetProducts()
{
var p1 = new Product { ID = 1, Description = "Product 1" };
var p2 = new Product { ID = 2, Description = "Product 2" };
var p3 = new Product { ID = 3, Description = "Product 3" };
var p4 = new Product { ID = 4, Description = "Product 4" };
var products = new List<Product> { p1, p2, p3, p4 };
return View(products);
}
}

You can use LINQ and pass the pageNumber and resultsPerPage to a controller.
var entries = _dbContext.YourTable.OrderBy(e => e.Date).Skip(pageNumber - 1).Take(resultsPerPage);
Your logic should also calculate how many pages there will be by getting the count of records for your particular query and doing some basic math.
Here's a good example: http://jasonwatmore.com/post/2015/10/30/ASPNET-MVC-Pagination-Example-with-Logic-like-Google.aspx

Related

Setting DropDownListFor default text MVC

I am new to MVC, and am trying to do something that should be easy, but it is eluding me. I am using a DropDownListFor in a partial view to display a list of product names. That part works fine. What I am having trouble with is setting the initial value of the DropDownListFor to display "Select one". The code I am working with is as follows:
#Html.DropDownListFor(model => model.ProductId, new SelectList(ViewBag.ProductData, "ProductId", "Name"), "---Select one---", new { htmlAttributes = new { #id = "ProductName" } });
The controller which sets the ViewBag is as follows:
public ActionResult AddProduct(int quoteId, int quoteDetailId)
{
var items = db.Products.ToList();
ViewBag.ProductData = items;
ViewData["QuoteId"] = quoteId;
ViewData["QuoteDetailId"] = quoteDetailId;
return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 1, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
}
Once I hit the dropdown arrow on the DropDownListFor, "Select one" appears at the top of the list. But when the DropDownListFor is first displayed, the first product name appears in the box, instead of "Select one". How can I fix this? Any help would be much appreciated.
Don't specify a value for the id property in your model:
public ActionResult AddProduct(int quoteId, int quoteDetailId)
{
var items = db.Products.ToList();
ViewBag.ProductData = items;
return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 0, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
}

asp.net mvc paging error

I have a pagination problem. I have a Product model, it has a string ProductCategory attribute. One page can take 4 products, whenever it exceeds 4, it points out page 2. The problem is that when I click "Car" category and click page 2, it takes every product, rather than taking only "Car" .
I got the book from the book, ASP.NET MVC 4, published by apress.
Here is my ProductListViewModel:
public class ProductsListViewModel
{
public List<Product> Products { get; set; }
public PagingInfo PagingInfo { get; set; }
public string CurrentCategory { get; set; }
}
Here is my ProductController's List Action: When I debug the application, at the click at page 2, category parameter is null.
public ViewResult List(string category, int page = 1)
{
ProductsListViewModel model = new ProductsListViewModel
{
Products = repository.Products
.Where(p => category == null || p.ProductCategory.Equals(category))
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize).Take(PageSize).ToList(),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = category == null ?
repository.Products.Count() :
repository.Products.Where(e => e.ProductCategory == category).Count()
}
};
model.CurrentCategory = category;
return View(model);
}
Here is my List View:
#model SportsStore.WebUI.Models.ProductsListViewModel
#{
ViewBag.Title = "Products";
}
#foreach (var p in Model.Products)
{
<div class="item">
#Html.Partial("ProductSummary", p)
</div>
}
<div class="pager">
#Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x, ProductCategory = Model.CurrentCategory }))
ProductSummary is a partial view that views the product. Pagelinks is a extention methods:
public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo,
Func<int, string> pageUrl)
{
StringBuilder result = new StringBuilder();
for (int i = 1; i <= pagingInfo.TotalPages; i++)
{
TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
tag.AddCssClass("selected");
result.Append(tag.ToString());
}
return MvcHtmlString.Create(result.ToString());
}
As pictured above, when I click page 2, it gets every product, rather than car. How can I solve it?
Thanks in advance.
NOTE: Routes has been added below:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(null,
"",
new
{
controller = "Product",
action = "List",
category = (string)null,
page = 1
}
);
/*
*http://localhost:56701/?page=2 olmasındansa http://localhost:56701/Page4 olmasını sağlayan kod parçacığı.
*
*/
routes.MapRoute(null,
"Page{page}",
new { controller = "Product", action = "List", category = (string)null },
new { page = #"\d+" }
);
routes.MapRoute(null,
"{category}",
new { controller = "Product", action = "List", page = 1 }
);
routes.MapRoute(null,
"{category}/Page{page}",
new { controller = "Product", action = "List" },
new { page = #"\d+" }
);
routes.MapRoute(null, "{controller}/{action}");
}
}
NOTE 2:
Here is the result when I click page 2 of the Car category:
As you see below, at the page 2, every car items exist. (Blue rectangle). But I do no want to see page 3 and 4 at the bottom of the page (Red rectangle).
Thanks in advance.
The solution has implemented in the book, and it seems it has been escaped from my attention.
Two revisions should be made in the source code, one in List.cshtml :
<div class="pager">
#Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x, category = Model.CurrentCategory }))
Another is in the List action of the ProductController:
public ViewResult List(string category, int page = 1)
{
ProductsListViewModel viewModel = new ProductsListViewModel
{
Products = repository.Products
.Where(p => category == null || p.ProductCategory == category)
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize).ToList(),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
**TotalItems = category == null ?
repository.Products.Count() :
repository.Products.Where(e => e.ProductCategory == category).Count()**
},
CurrentCategory = category
};
return View(viewModel);
}
TotalItems attribute shall be updated as mentioned above.

how to give textox dynamically at runtime in mvc4 bootstrap

HI i am new to mvc and bootstrap.. i want to dynamically add two text box at run time in mvc4 and bootstrap.. i have tried many sites but i am not able to understand. please give me simple example
i have tried this
In model
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
}
in controller
public ActionResult PanelEx()
{
var initialData = new[] {
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
what should i wrote in model. how to do next step..i am stuck PLese help
public ActionResult PanelEx()
{
var initialData = new List<Gift>{
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
#model IEnumerable<Gift>
<div>
#foreach(var item in Model)
{
<div>
#Html.TextBoxFor(item=>item.Name)
</div>
}
</div>

More Elegant way to return json array to ASP.NET MVC

{Sorry new to JSON}
I need to build up an array of resources (Users) and pass it in to my view, might be a better way than what ive done below? (Demo)
My model is simply
public class ScheduleUsers
{
public string Resource{ get; set; }
}
On my controller
var users = new JsonArray(
new JsonObject(
new KeyValuePair<string,JsonValue>("id","1"),
new KeyValuePair<string,JsonValue>("name","User1")),
new JsonObject(
new KeyValuePair<string, JsonValue>("id", "2"),
new KeyValuePair<string, JsonValue>("name", "User2"))
);
model.Resources = users.ToString();
Why don't you just return a list of entities as a JSON result, like:
public class CarsController : Controller
{
public JsonResult GetCars()
{
List<Car> cars = new List<Car>();
// add cars to the cars collection
return this.Json(cars, JsonRequestBehavior.AllowGet);
}
}
It will be converted to JSON automatically.
I did this and this works
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
//Serialize
js.Serialize(GetResources(), sb);
public List<ScheduledResource> GetResources()
{
var res = new List<ScheduledResource>()
{
new ScheduledResource()
{
id = "1",
color = "blue",
name = "User 1"
},
new ScheduledResource()
{
id = "2",
color = "black",
name = "User 2"
},
};
return res;
}

Custom grid using Telerik pluggin in nopcommerce 2.8

Iam working on nopcommerce2.8 version. I have a problem with telerik plugin implementation to create new grid.
Iam implementing a concept where for a product i want to give different price for different customer. So to assign new price for different customers, in admin panel i am creating a grid in edit productvariant page using telerik. I have created a new tab to display these details. Iam able to display customer name and price in grid, but i am not able to call update function, when i click on update button after editing a row. The same update function i called for Deleting the grid row also, so when i click on delete the same update function getting trigger. I think some setting has been missed in View. Please help me to solve this update issue.
The model, view and controller of my nopcommerce in given below.
Thanks.
//Model
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using FluentValidation.Attributes;
using Nop.Admin.Models.Customers;
using Nop.Admin.Validators.Catalog;
using Nop.Web.Framework;
using Nop.Web.Framework.Localization;
using Nop.Web.Framework.Mvc;
using Telerik.Web.Mvc;
namespace Nop.Admin.Models.Catalog
{
public partial class CustomerProductPriceModel : BaseNopModel
{
public int Customer_Id { get; set; }
[NopResourceDisplayName("Customer Name")]
public string Customer_name { get; set; }
[NopResourceDisplayName("Price")]
public decimal Price { get; set; }
[NopResourceDisplayName("Unit")]
public string Units { get; set; }
}
}
// view
#(Html.Telerik().Grid<CustomerProductPriceModel>()
.Name("Grid")
.DataKeys(x =>
{
x.Add(y => y.Customer_Id);
})
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("CustomerProductPriceList", "ProductVariant", new { productVariantId = Model.Id })
.Update("CustomerPriceUpdate", "ProductVariant", new { productVariantId = Model.Id })
.Delete("CustomerPriceUpdate", "ProductVariant", new { productVariantId = Model.Id });
})
.Columns(columns =>
{
columns.Bound(y => y.Customer_name).Width(200).ReadOnly();
columns.Bound(y => y.Price).Width(100);
columns.Command(commands =>
{
commands.Edit().Text(T("Admin.Common.Edit").Text);
commands.Delete().Text(T("Admin.Common.Delete").Text);
}).Width(180);
})
.Editable(x =>
{
x.Mode(GridEditMode.InLine);
})
.EnableCustomBinding(true)
)
// controller
[GridAction(EnableCustomBinding = true)]
public ActionResult CustomerPriceUpdate(GridCommand command, CustomerProductPriceModel model, int productVariantId)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
return AccessDeniedView();
return CustomerProductPriceList(command, productVariantId);
}
[HttpPost, GridAction(EnableCustomBinding = true)]
public ActionResult CustomerProductPriceList(GridCommand command, int productVariantId)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
return AccessDeniedView();
var productVariant = _productService.GetProductVariantById(productVariantId);
if (productVariant == null)
throw new ArgumentException("No product variant found with the specified id");
var CustomerPrices = PrepareCustomerProductPriceModel(productVariant.Product.Id);
var CustomerPricesa = CustomerPrices
.Select(x =>
{
return new CustomerProductPriceModel()
{
Customer_Id = x.Customer_Id,
Price = x.Price,
Units = x.Units,
Customer_name = x.Customer_name
};
})
.ToList();
var model = new GridModel<CustomerProductPriceModel>
{
Data = CustomerPricesa,
Total = CustomerPrices.Count
};
return new JsonResult
{
Data = model
};
}
Is there a reason not to use the built-in customer price levels already in place in nopCommerce, or are you wanting to display all prices at once?

Resources