load one item per page [ Pagination ] - c#

I have a viewpage like below
this is the controller method for above view
public ActionResult Add_Product()
{
var model = new AddNewProduct
{
ListProductFields = db.AB_ProductTypeCategoryField.ToList()
};
return View(model);
}
this is model class for above view
public class AddNewProduct
{
public string Product_ID { get; set; }
public string ProductTypeID { get; set; }
public string ProductCategoryID { get; set; }
public string Subsidary_ID { get; set; }
public IList<AB_ProductTypeCategoryField> ListProductFields { get; set; }
}
public partial class AB_ProductTypeCategoryField
{
public string Field_Value_EN { get; set; }
public string Field_Value_AR { get; set; }
}
this is viewpage
#model albaraka.Models.AddNewProduct
#using (Html.BeginForm())
{
#for (int i = 0; i < Model.ListProductFields.Count; i++)
{
#Html.TextAreaFor(m => m.ListProductFields[i].Field_Value_EN, new { #class = "form-control summernote", #row = 5 })
#Html.TextAreaFor(m => m.ListProductFields[i].Field_Value_AR, new { #class = "form-control summernote", #row = 5 })
}
}
Now I want to add pagination for above view page and limit one ListProductFields per one page , for that I following this Tutorial
So I change my code to like this
public ActionResult Add_Product(int? page)
{
var dummyItems = db.AB_ProductTypeCategoryField.Select(x => "Item " + x);
var pager = new PaginationModel.Pager(dummyItems.Count(), page);
var model = new AddNewProduct
{
Items = dummyItems.Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
Pager = pager
};
return View(model);
}
But then I'm getting following Run-time Error
Values of type 'AB_ProductTypeCategoryField' can not be converted to string.

Just try with following code , so you cannot use Skip method alone. so have use OrderBy before it
var dummyItems = db.AB_ProductTypeCategoryField;
var pager = new PaginationModel.Pager(dummyItems.Count(), page);
var model = new AddNewProduct
{
ListProductFields = dummyItems.OrderBy(i => i.SomeProperty).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
Pager = pager
};
return View(model);

The issue of your observation is below line
var dummyItems = db.AB_ProductTypeCategoryField.Select(x => "Item " + x);
Since you are trying to select object with string concatenate operation ("Item " + x) that's why exception is thrown as AB_ProductTypeCategoryField is an object. I don't think you require "Item " + x at all.
You can change AddNewProdcut action implementation as
public ActionResult Add_Product(int? page)
{
var pager = new PaginationModel.Pager(dummyItems.Count(), page);
var model = new AddNewProduct
{
ListProductFields = db.AB_ProductTypeCategoryField.Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
Pager = pager
};
return View(model);
}

Related

How to pass more than 2 values into SelectList (DropdownList)

I have the below code which pass 2 values (ProductId and ItemName) to SelectList (Dropdownlist) located on the View.
I need a way to pass 3 values (ProductId, Price, and ItemName).
public class Product
{
public int ProductId { get; set; }
public int Price { get; set; }
public string ItemName { get; set; }
public IList<ProductInvoice> ProductInvoices { get; set; }
}
public IActionResult Create()
{
IEnumerable<SelectListItem> items = _context.Products.Select(c => new SelectListItem
{
Value = c.ProductId.ToString() + "-" + c.Price,
Text = c.ItemName
});
ViewData["Products"] = items;
return View();
}
Code to generate drop down list:
#Html.DropDownList("SelectedProducts",new SelectList((System.Collections.IEnumerable)ViewData["Products"], "Value", "Text", new { #class = "form-control dropdown-list" }))
You can join every property you need by a delimiter and pass it to Value. Like this:
IEnumerable<SelectListItem> items = _context.Products.Select(c => new SelectListItem
{
Value = String.Join("$", new string[] { c.ProductId.ToString(), c.Price }),
Text = c.ItemName
});
and when fetching back, you can perform a split with the delimiter. Like this:
var myVal = value.Split("$");
string productId = myVal[0];
string price = myVal[1];
You made almost right thing, only if you want to see the price you have to concat it with Name, not with Id
public IActionResult Create()
{
var selectListItems= _context.Products.Select(c => new SelectListItem
{
Value = c.ProductId.ToString(),
Text = c.ItemName+ " - " + c.Price.ToString()
});
var items= new SelectList( selectListItems,"Value", "Text");
ViewData["Products"] = items;
var model=new Product();
return View( model);
}
and fix the view
#Html.DropDownListFor(m=> m.ProductId, (SelectList) ViewData["Products"], new { #class = "form-control dropdown-list" }))

Pagedlist Pagination without Parameters MVC

I am using Pagedlist for Pagination in my MVC project. Pagination is working for most of the cases without ViewModels.
But when I use a ViewModel PagedList generating Pagination links but without any parameter value to querystring page.
Here is my ViewModel
public class SearchResult
{
public int ItemID { get; set; }
public string ItemTitle { get; set; }
public int? AuthorID { get; set; }
public string AuthorName { get; set; }
public int? IssueDate { get; set; }
}
And ActionResult Method
public ActionResult Date(int? page)
{
try
{
string query;
if (Request.RequestContext.RouteData.Values["query"] != null)
{
using (dreposEntities db = new dreposEntities())
{
query = Request.RequestContext.RouteData.Values["query"].ToString();
int issueYear = int.Parse(query);
ViewBag.Query = issueYear;
var dateFilter = db.itemstreams.Where(q => q.issuedate == issueYear).ToList();
List<SearchResult> resultList = new List<SearchResult>();
if (dateFilter.Any())
{
foreach (var c in dateFilter)
{
SearchResult obj = new SearchResult
{
ItemID = c.id,
ItemTitle = c.title,
IssueDate = c.issuedate,
};
resultList.Add(obj);
}
}
ViewBag.SearchQuery = query;
return View(resultList.OrderBy(d=>d.IssueDate).ToPagedList(page ?? 1, 10));
}
}
else
{
using (dreposEntities db = new dreposEntities())
{
List<SearchResult> resultList = new List<SearchResult>();
var files = db.itemstreams.Where(s=>s.status==1).ToList();
if (files.Any())
{
foreach (var f in files)
{
SearchResult obj = new SearchResult
{
ItemID = f.id,
ItemTitle = f.title,
IssueDate = f.issuedate,
};
resultList.Add(obj);
}
}
return View(resultList.OrderBy(d=>d.IssueDate).ToPagedList(page ?? 1, 10));
}
}
}
catch (Exception e)
{
return View();
}
}
What above code is showing in View is attached in below email
And in View/Razor
<div class="pull-right">
#Html.PagedListPager(Model, page => Url.Action("Date", new { page }), new PagedListRenderOptions() { Display = PagedListDisplayMode.IfNeeded })
</div>

LinQ to SQL missing data

I'm trying to get all rows from my SANPHAM table but somehow it keeps missing some rows. The table has 9 rows, however, when displayed, it show only 5 rows (I have picture below, and don't mind about products' image, I will add the rests later).
I have tried to do something in my code, I change int i = 0 to int i = 1 and there are 2 situations. With i = 0, the result misses even rows and with i = 1, odd rows disappear.
I am a newbie to this, I looked for some solutions but still can't fix it, hope you guys can help
Here is my code:
HomeControllers.cs:
namespace MvcApplication.Controllers
{
public class HomeController : Controller
{
private LinQtoSQLDataContext LinQtoSQLDataContext = new LinQtoSQLDataContext();
public ActionResult Index()
{
IList<Models.SanPhamModels> sanPhamList = new List<Models.SanPhamModels>();
var query = from sanpham in LinQtoSQLDataContext.SANPHAMs select sanpham;
var sps = query.ToList();
foreach (var sanPhamData in sps)
{
sanPhamList.Add(new Models.SanPhamModels()
{
maSanPham = sanPhamData.maSanPham,
tenSanPham = sanPhamData.tenSanPham,
gia = sanPhamData.gia,
tacGia = sanPhamData.tacGia,
moTa = sanPhamData.moTa,
maDanhMuc = sanPhamData.maDanhMuc,
hinhAnh = sanPhamData.hinhAnh
});
}
return View(sanPhamList);
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Index.cshtml:
#for (int i=0; i<Model.Count; i++)
{
var tmp = "<div class=\"product_box\">";
tmp += "<img src=\""+ Url.Content(Model[i].hinhAnh) + "\" alt=\"Image\" /><br>";
tmp += Html.ActionLink(Model[i].tenSanPham, "productdetail", new { maSanPham = Model[i].maSanPham }, null);
tmp += "<p class=\'product_price\">" + Model[i].gia.ToString() + "</p>";
tmp += Html.ActionLink("Add to Cart", "shoppingcart", new { maSanPham = Model[i].maSanPham }, new {#class = "add_to_card"});
tmp += Html.ActionLink("Detail", "productdetail", new { maSanPham = Model[i].maSanPham }, new { #class = "detail" });
tmp += "</div>";
#Html.Raw(tmp)
}
SanPhamModels:
namespace MvcApplication.Models
{
public class SanPhamModels
{
public string maSanPham { get; set; }
public string tenSanPham { get; set; }
public double gia { get; set; }
public string tacGia { get; set; }
public string moTa { get; set; }
public string maDanhMuc { get; set; }
public string hinhAnh { get; set; }
}
}
My database
My website result image
EDITED:
I see what problem with my project:
Problem
a <div> inside a <div> so that it shows only the odd rows or even rows. Now I am working on this issue, still need some help...
you have to define the model in top with list as you are returning the list from controller.
#model IEnumerable<Models.SanPhamModels>

#Html.DropDownList not showing selected value

I am trying to create one partial view to create drop down on every view. Have created one view model and partial view for the same. Its creating drop down properly but not showing selected value.
Below is View Model Class
public class drowDownVM
{
public string id { get; set; }
public string name { get; set; }
public string cssClass { get; set; }
public string keyColumnName { get; set; }
public string valueColumnName { get; set; }
public string selectedValue { get; set; }
public string viewbagName { get; set; }
public bool isMultipleSelect { get; set; }
public List<int> multipleselectedValue { get; set; }
}
Below is partial view to bind drop down
#if (Model != null)
{
if (ViewData != null && ViewData.Count > 0 && ViewData.Keys.Contains(Model.viewbagName))
{
string ddName = !(string.IsNullOrEmpty(Model.name)) ? Model.name : "default-name";
string viewBagName = !(string.IsNullOrEmpty(Model.viewbagName)) ? Model.viewbagName : ViewData.Keys.First();
string keyColumnName = !(string.IsNullOrEmpty(Model.keyColumnName)) ? Model.keyColumnName : "id";
string valueColumnName = !(string.IsNullOrEmpty(Model.valueColumnName)) ? Model.valueColumnName : "id";
string selectedVal = !(string.IsNullOrEmpty(Model.selectedValue)) ? Model.selectedValue : "";
List<int> multipleSelectVal = (Model.multipleselectedValue != null && Model.multipleselectedValue.Count > 0) ? Model.multipleselectedValue : new List<int>();
var cssClass = !(string.IsNullOrEmpty(Model.cssClass)) ? Model.cssClass : "";
if (!Model.isMultipleSelect)
{
<div>
#Html.DropDownList(ddName, new SelectList((System.Collections.IEnumerable)ViewData[viewBagName], keyColumnName, valueColumnName, 2), "--Select--", new { #class = cssClass, #data_Val = selectedVal })
</div>
}
else
{
#Html.ListBox(ddName, new MultiSelectList((System.Collections.IEnumerable)ViewData[viewBagName], keyColumnName, valueColumnName, multipleSelectVal), new { #class = cssClass, #multiple = "multiple"})
}
}
}
else
{
<p class="hidden">Model Data Not Found!</p>
}
Below is the code which calls partial view to bind drop down, first one is single select, second one is calling multiple select.
#Html.Partial("_dropdown", new drowDownVM() { cssClass = "form-control", id = "TargetTypeList", keyColumnName = "code_val", name = "TargetTypeList", selectedValue = "1", valueColumnName = "code_name", viewbagName = "TargetTypeList"})
#Html.Partial("_dropdown", new drowDownVM() { cssClass = "form-control", id = "TargetTypeList", isMultipleSelect = true, keyColumnName = "code_val", name = "TargetTypeList", selectedValue = "1", valueColumnName = "code_name", viewbagName = "TargetTypeList", multipleselectedValue = new List<int>() { 1, 2 } })
<div>
#Html.DropDownList(ddName, new SelectList((System.Collections.IEnumerable)ViewData[#ViewBag.ViewBagName], keyColumnName, valueColumnName, 2), "--Select--", new { #class = cssClass, #data_Val = selectedVal })
</div>

Recursive call of #helper method in ASP.NET MVC Razor, code inside the #helper method is skipped during execution

I am trying to populate the nested Ordered list using #functions & #helper features in ASP.NET MVC Razor.
I am successful in creating nested list using #functions, but when I tried to the same with #helper method execution is not going inside the helper method.
Model:
public class NavigationMenuModels
{
public int ID { get; set; }
public int? ParentID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<NavigationMenuModels> SubNavigationMenu { get; set; }
}
View Model:
public class NavigationMenuViewModel
{
public NavigationMenuViewModel()
{
ListMenu = new List<NavigationMenuModels>();
}
public string ListName { get; set; }
public List<NavigationMenuModels> ListMenu { get; set; }
}
Controller:
public ActionResult NavigationMenu()
{
//Menu
NavigationMenuModels objMenu = new NavigationMenuModels() { ID = 1, ParentID = null, Name = "Menu", Description = "Menu" };
//Menu Items
List<NavigationMenuModels> objMenuItems = new List<NavigationMenuModels>();
objMenuItems.Add(new NavigationMenuModels() { ID = 1, ParentID = 1, Name = "Home", Description = "Home" });
objMenuItems.Add(new NavigationMenuModels() { ID = 2, ParentID = 1, Name = "About", Description = "About" });
objMenuItems.Add(new NavigationMenuModels() { ID = 3, ParentID = 1, Name = "Help", Description = "Help" });
objMenuItems.Add(new NavigationMenuModels() { ID = 4, ParentID = 1, Name = "Contact", Description = "Contact" });
objMenu.SubNavigationMenu = objMenuItems;
//Admin
NavigationMenuModels objAdmin = new NavigationMenuModels() { ID = 2, ParentID = null, Name = "Admin", Description = "Admin" };
//Admin Items
List<NavigationMenuModels> objAdminItems = new List<NavigationMenuModels>();
objAdminItems.Add(new NavigationMenuModels() { ID = 1, ParentID=2, Name = "User Permissions", Description = "User Permissions" });
objAdminItems.Add(new NavigationMenuModels() { ID = 2, ParentID=2, Name = "Security", Description = "Security" });
objAdmin.SubNavigationMenu = objAdminItems;
//Account
NavigationMenuModels objAccount = new NavigationMenuModels() { ID = 3, ParentID = null, Name = "Account", Description = "Account" };
//Account Items
List<NavigationMenuModels> objAccountItems = new List<NavigationMenuModels>();
objAccountItems = null;
objAccount.SubNavigationMenu = objAccountItems;
NavigationMenuViewModel objNavigationMenu = new NavigationMenuViewModel();
objNavigationMenu.ListName = "Master Navigation";
objNavigationMenu.ListMenu.Add(objMenu);
objNavigationMenu.ListMenu.Add(objAdmin);
objNavigationMenu.ListMenu.Add(objAccount);
return View(objNavigationMenu);
}
CSHTML:
#using LearnAngularJs_App1.Models
#using System.Text
#model LearnAngularJs_App1.Models.NavigationMenuViewModel
#{
ViewBag.Title = "NavigationMenu";
}
#functions
{
public static HtmlString GetNestedListHtml(NavigationMenuViewModel Crudeinput)
{
StringBuilder sb = new StringBuilder();
var orderedList = new TagBuilder("ol");
foreach (NavigationMenuModels NavMenu in Crudeinput.ListMenu)
{
var listItem = new TagBuilder("li");
listItem.SetInnerText(NavMenu.Name);
sb.AppendLine(listItem.ToString(TagRenderMode.Normal));
if (NavMenu.SubNavigationMenu != null)
{
if (NavMenu.SubNavigationMenu.Count > 0)
{
sb.AppendLine(BuildNestedList(NavMenu.SubNavigationMenu));
}
}
}
orderedList.InnerHtml = sb.ToString();
return new HtmlString(orderedList.ToString(TagRenderMode.Normal));
}
public static string BuildNestedList(List<NavigationMenuModels> SubMenuList)
{
var sb = new StringBuilder();
var orderedList = new TagBuilder("ol");
if (SubMenuList.Count > 0)
{
foreach (NavigationMenuModels SubNavgationMenuitem in SubMenuList)
{
var listItem = new TagBuilder("li");
listItem.SetInnerText(SubNavgationMenuitem.Name);
sb.AppendLine(listItem.ToString(TagRenderMode.Normal));
if (SubNavgationMenuitem.SubNavigationMenu != null)
{
if (SubNavgationMenuitem.SubNavigationMenu.Count > 0)
{
sb.AppendLine(BuildNestedList(SubNavgationMenuitem.SubNavigationMenu));
}
}
}
}
orderedList.InnerHtml = sb.ToString();
return orderedList.ToString(TagRenderMode.Normal);
}
}
#helper BuildNestedListHelper(List<NavigationMenuModels> Crudeinput)
{
if (Crudeinput.Any())
{
<ol>
#foreach (NavigationMenuModels NavMenu in Crudeinput)
{
<li>
#NavMenu.Name
#if (NavMenu.SubNavigationMenu != null)
{
BuildNestedListHelper(NavMenu.SubNavigationMenu);
}
</li>
}
</ol>
}
}
<h2>NavigationMenu</h2>
<div>
<div><span>Bind Navigation Menu using razor ##funtions</span></div>
<div>
#GetNestedListHtml(Model)
</div>
</div>
<div>
<div><span>Bind Navigation Menu using razor ##helper</span></div>
<div>
#BuildNestedListHelper(Model.ListMenu)
</div>
</div>
When a recursive call to the helper method is made execution is going to the method, but the execution is skipped.
just add "#" in front of the method when recursive call.

Categories

Resources