Implementing pagination - asp.net-mvc-4

I have the following action
public ActionResult ViewModelProducts()
{
var listOfProductsBuy = db.ProductsBuy.Select(x => new ProductBuyViewModel
{
Id = x.Id,
Title = x.Title,
ProductBuyId = x.Id,
Author = x.Author,
MasterImageUrl = x.Images.FirstOrDefault().Url,
Price = x.Price,
Values = x.Value,
}).ToList();
var listOfProductsRent = db.ProductsRent.Select(y => new ProductRentViewModel
{
Id = y.Id,
Title = y.Title,
MasterImageUrl = y.ImagesRent.FirstOrDefault().Url,
ProductRentId = y.Id,
Author = y.Author,
Period = y.Period.PeriodOfTime,
Price = y.Price,
Values = y.Value,
}).ToList();
var listOfProductsSearch = db.ProductSearches.Select(z => new ProductSearchViewModel
{
Id = z.Id,
Title = z.Title,
ProductSearchId = z.Id,
Author = z.Author,
MasterImageUrl = z.ImagesSearch.FirstOrDefault().Url,
Price = z.Price,
Values = z.Value,
}).ToList();
var viewModel = new AllProductsViewModel { ProductBuy = listOfProductsBuy, ProductRent = listOfProductsRent, ProductSearch = listOfProductsSearch};
return View(viewModel);
}
I want to implement paging for more than one viewmodel. If there is way with PagedList it will be better, but if there is not it will be ok too.

In order to add paging, you can install PagedList.MVC Nuget package. You can see the exact step by step procedure to add it on Microsoft website here. Check out the section named: "Add Paging to the Students Index Page". Hope this helps.

Related

Im using datatable in my project mvc , i want display Categorie name in place of categorye id foreign key in table courses

[HttpGet]
public JsonResult GetData()
{``
ApplicationDbContext db = new ApplicationDbContext();
var course = db.Courses
.Include(d=>d.Competences)
.Include(d=>d.Sequences)
.ToList().Select(p => new { Id = p.Id, Titre = p.Titre, ShortDescription = p.ShortDescription, Price = p.Price, CategorieId = p.CategorieId });
var query = from q in db.Courses
join cat in db.Categories.AsEnumerable()
on q.CategorieId equals cat.Libelle
enter code here
return Json(new { data = course },
JsonRequestBehavior.AllowGet);
}

Convert EntityFramework to Raw SQL Queries in MVC

I am trying to make a crud calendar in my .net, my question is, How do make the below entity framework codes to SQL queries?
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
dc.Events.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
Thanks guys
You can run raw query in entity framework with dc.Database.ExecuteSqlCommand() command like below:
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
dc.Database.ExecuteSqlCommand(&#"
UPDATE Events
SET Subject = {e.Subject},
Start = {e.Start},
End = {End},
Description = {Description},
IsFullDay = {IsFullDay},
ThemeColor = {ThemeColor},
WHERE EventID = {e.EventID}
IF ##ROWCOUNT = 0
INSERT INTO Events (EventID, Subject, Start, End, Description, IsFullDay, ThemeColor)
VALUES ({e.EventID}, {e.Subject}, ...)
");
status = true;
}
return new JsonResult { Data = new { status = status }
};

How to Increase performance of API call

I am using 5 Hotels APIs and trying to combine and pick min price hotel with unique hotels from all APIs. I am following these STEPS
Call All 5 APIsand wait for response.
get all static data from database or if avail my server caching(all 5 APIs like hotels name, images, desc, etc)
Combine into one custom class
get GIATA map codes from caching or database.
Apply GIATA into API result and group all hotels with unique GIATA id.
Pick min price .
Bind UI and show to customer.
string sessionid = sqf;
DS.Models.BL.Common.HotelSearchDetails details = new DS.Models.BL.Common.HotelSearchDetails();
details = (.Models.BL.Common.HotelSearchDetails)Session["Details_" + sessionid];
List<DS.BL.Common.HotelDetails> DOTWhdlist = new List<DS.BL.Common.HotelDetails>();
List<DS.BL.Common.HotelDetails> GTAhdlist = new List<DS.BL.Common.HotelDetails>();
List<DS.BL.Common.HotelDetails> HPhdlist = new List<DS.BL.Common.HotelDetails>();
List<DS.BL.Common.HotelDetails> HBhdlist = new List<DS.BL.Common.HotelDetails>();
List<DS.BL.Common.HotelDetails> TSGhdlist = new List<DS.BL.Common.HotelDetails>();
//GTA City Cache
DS.Models.BL.GTA_Model.Methods.HotelInfo hinfo = new Models.BL.GTA_Model.Methods.HotelInfo();
List<GTA.API.HotelSearch.GTAHotels> hlist = new List<GTA.API.HotelSearch.GTAHotels>();
hlist = hinfo.GethotellistCityWise(details.GTACityCode);
//
/*************************************************
* DOTW cache
*
*************************************************/
DS.BL.DOTW.Method.HotelInfo objhoteldetails = new DS.BL.DOTW.Method.HotelInfo();
Dictionary<string, int> dictionary = objhoteldetails.Gethotelratings();
List<DOTW.Method.searchhotels.DotwHotels> objhotellist = new List<DOTW.Method.searchhotels.DotwHotels>();
objhotellist = objhoteldetails.GethotellistCityWise(details.DOTWCityCode);
//-------------------------------------------------------------------------------------------------------
//------Hotel pro cache city
DS.BL.HotelsPro.Method.GetHotelDetails objhoteldetails_hp = new BL.HotelsPro.Method.GetHotelDetails();
List<HotelsPro.Method.Avail.HotelsProHotels> objhotellist_hp = new List<HotelsPro.Method.Avail.HotelsProHotels>();
objhotellist_hp = objhoteldetails_hp.GethotellistCityWise(details.HotelsProCityCode);
/***************************************************
* Hotelbeds city cache
*
*/
DS.Models.BL.HotelBeds.Methods.HotelInfoController objhotelbeds = new DS.Models.BL.HotelBeds.Methods.HotelInfoController();
List<HotelBeds.Method.SearchHotel.HotelBedsHotels> HBhotellist = new List<HotelBeds.Method.SearchHotel.HotelBedsHotels>();
HBhotellist = objhotelbeds.GethotellistCityWise(details.HBCityCode);
/**************************************************
*
* TSG city cache
*
*/
DS.Models.BL.TSG.Methods.HotelInfo objtsg_hotel = new Models.BL.TSG.Methods.HotelInfo();
List<TSG.API.HotelAvail.TSGHotels> TSGhlist = new List<TSG.API.HotelAvail.TSGHotels>();
TSGhlist = objtsg_hotel.GethotellistCityWise(details.City);
//---------------------------------------------------------------------------------------------------------------------
var dotw = Task<List<DS.BL.Common.HotelDetails>>.Factory.StartNew(() => Dotw(sqf, details, dictionary, objhotellist));
var gta = Task<List<DS.BL.Common.HotelDetails>>.Factory.StartNew(() => GTA(sqf, details, hlist));
var hotelpro = Task<List<DS.BL.Common.HotelDetails>>.Factory.StartNew(() => Hp(sqf, details, objhotellist_hp));
var hotelbeds = Task<List<DS.BL.Common.HotelDetails>>.Factory.StartNew(() => HB(sqf, details, HBhotellist));
var tsg = Task<List<DS.BL.Common.HotelDetails>>.Factory.StartNew(() => TSG(sqf, details, TSGhlist));
DOTWhdlist = dotw.Result;
TSGhdlist = tsg.Result;
GTAhdlist = gta.Result;
HPhdlist = hotelpro.Result;
HBhdlist = hotelbeds.Result;
ViewBag.sessionId = sessionid;
DOTWhdlist.AddRange(GTAhdlist);
DOTWhdlist.AddRange(HPhdlist);
DOTWhdlist.AddRange(HBhdlist);
DOTWhdlist.AddRange(TSGhdlist);
string[] c = details.CityName.Split(',');
string cityname = c[0];
List<DS.BL.Common.HotelDetails> filterdata = GiataApply(DOTWhdlist, cityname, details.GiataCityid);
List<DS.BL.Common.HotelDetails> tsgdata = filterdata.Where(x => x.giataref == "exclusivelyhotels").ToList();
List<DS.BL.Common.HotelDetails> gtadata = filterdata.Where(x => x.giataref == "gta").ToList();
List<DS.BL.Common.HotelDetails> dotwdata = filterdata.Where(x => x.giataref == "DOTW").ToList();
List<DS.BL.Common.HotelDetails> hpdata = filterdata.Where(x => x.giataref == "metglobal").ToList();
List<DS.BL.Common.HotelDetails> hbdata = filterdata.Where(x => x.giataref == "hotelbeds").ToList();
allSup.dotw = dotwdata;
GIATA APPLY
List<DS.BL.Common.HotelDetails> GiataApply(List<DS.BL.Common.HotelDetails> hlist, string city, int Cityid)
{
DS.Models.BL.Common.GIATA.giataCodes giataCodes = new Models.BL.Common.GIATA.giataCodes();
List<GiataProperty> gcode = new List<GiataProperty>();
gcode = giataCodes.GiataCodes(city, Cityid);
var query = from h in hlist
join g in gcode on new { hotelcode = h.HotelId, supcode = h.giataref }
equals new { hotelcode = g.Hcode, supcode = g.ProviderCode }
select new DS.BL.Common.HotelDetails
{
HotelName = h.HotelName,
HCode = h.HCode,
HotelId = h.HotelId,
Address = h.Address,
image = h.image,
location = h.location,
Currency = h.Currency,
searchId = h.searchId,
Price = h.Price,
rating = h.rating,
hoteldescription = h.hoteldescription,
Latitude = h.Latitude,
Longitude = h.Longitude,
imagelist = h.imagelist,
Source = h.Source,
giataref = h.giataref,
HFullResponse = h.HFullResponse,
AvailableRoomList = h.AvailableRoomList,
HotelRooms = h.HotelRooms,
facilities = h.facilities,
faDetails = h.faDetails,
giata = g.giataId.Value,
hotelservices = h.hotelservices,
gtaIDref = h.gtaIDref
};
var filter = from x in query
group x by x.giata into hotels
select new DS.BL.Common.HotelDetails
{
HotelName = hotels.FirstOrDefault().HotelName,
HCode = hotels.FirstOrDefault().HCode,
HotelId = hotels.FirstOrDefault().HotelId,
Address = hotels.FirstOrDefault().Address,
image = hotels.FirstOrDefault().image,
location = hotels.FirstOrDefault().location,
Currency = hotels.FirstOrDefault().Currency,
searchId = hotels.FirstOrDefault().searchId,
imagelist = hotels.FirstOrDefault().imagelist,
Price = hotels.Min(p => p.Price),
rating = hotels.FirstOrDefault().rating,
hoteldescription = hotels.FirstOrDefault().hoteldescription,
Latitude = hotels.FirstOrDefault().Latitude,
Longitude = hotels.FirstOrDefault().Longitude,
Source = hotels.FirstOrDefault().Source,
giataref = hotels.FirstOrDefault().giataref,
HFullResponse = hotels.FirstOrDefault().HFullResponse,
AvailableRoomList = hotels.FirstOrDefault().AvailableRoomList,
HotelRooms = hotels.FirstOrDefault().HotelRooms,
facilities = hotels.FirstOrDefault().facilities,
faDetails = hotels.FirstOrDefault().faDetails,
giata = hotels.FirstOrDefault().giata,
hotelservices = hotels.FirstOrDefault().hotelservices,
gtaIDref = hotels.FirstOrDefault().gtaIDref
};
return filter.ToList();
//return query.ToList();
}
No this process taking 30-45 sec . i want to reduce i dont know how i do but in API calling i need to reduce time and GIATA apply .
give me idea guys thanks
Find async version of your API calls and use them. That should solve your problem. If no async version is available then you will have to do it in your code of C#. I am not a C# expert so I cannot help you there.

error 'Int32 ToInt32(System.String)'

i have added follow action to get products accroding to cat.id.
[HttpPost]
public ActionResult OnlineHome(string CategoryId)
{
OnlineDataModel dm = new OnlineDataModel();
dm.CatagoryData = new List<category>();
dm.ProductData = new List<product>();
dm.CatagoryData = db.categories.ToList();
//dm.ProductData = (from p in db.products where p.CategoryID == Convert.ToInt32(CategoryId) select p).ToList() ;
var data= db.products.Where(d => d.CategoryID == Convert.ToInt32(CategoryId)).ToList();
return View(dm);
}
I am getting following error
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and >this method cannot be translated into a store expression.
need a solution for this.
Solution 1:
Try to declare you Integer variable first:
int iCategoryId = Convert.ToInt32(CategoryId);
Then update your code to:
var data= db.products.Where(d => d.CategoryID == iCategoryId).ToList();
Solution 2 (recommended):
Make sure your action receives an integer and modify the type of the variable:
public ActionResult OnlineHome(int CategoryId)
Then update your code the same way to:
var data = db.products.Where(d => d.CategoryID == CategoryId).ToList();
Feel free to add your own cast validations to both solutions.
Do like this.
int catId = Convert.ToInt32(CategoryId);
var data = db.products.Where(d => d.CategoryID == catId).ToList();

How to populate a Chart ( Using System.Web.Helpers.Chart ) in LinqPad?

I have the code below, run it in LinqPad 4.40.03 + Sql Server 2008 R2 + NorthWind.
LinqPad return exception: "ArgumentNullException: Value cannot be null. Parameter name: httpContext".
Please give me the Final Fixed code, I want it populate a chart ( Using System.Web.Helpers.Chart ) in linqpad output screen.
void Main()
{
var q = from p in Products
let s = p.OrderDetails.Sum(o => o.Quantity) * p.UnitPrice
orderby s
select new { ProductName = p.ProductName, Sales = s};
var basicChart = new System.Web.Helpers.Chart(width: 600, height: 400)
.AddTitle("Product Sales")
.DataBindTable(dataSource: q, xField: "ProductName")
.Write();
basicChart.Dump();
}
The ASP.NET charting control relies on HttpContext.Current which is present only when running an ASP.NET application.
You could try mocking an HttpContext, or else use the charting control in System.Windows.Forms.DataVisualization.Charting instead:
var q = from p in Products
let s = p.OrderDetails.Sum(o => o.Quantity) * p.UnitPrice
orderby s
select new { ProductName = p.ProductName, Sales = s};
var chart = new Chart();
var ca = new ChartArea();
ca.AxisX.LabelStyle.Interval = 1;
chart.ChartAreas.Add (ca);
var series = new Series { ChartType = SeriesChartType.Bar};
series.Points.DataBind (q.Take(20), "ProductName", "Sales", null);
chart.Series.Add (series);
chart.Dump ("Chart");