Pagedlist Pagination without Parameters MVC - c#

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>

Related

c# how to access all instances of a class outside of the function?

I am new to C# and OOP, in general, I've kinda hit a wall I am reading in this CSV using the CSV Helper package, but there are some unwanted rows, etc so I have cleaned it up by iterating over "records" and creating a new class LineItems.
But Now I appear to be a bit stuck. I know void doesn't return anything and is a bit of a placeholder. But How can I access all the instances of LineItems outside of this function?
public void getMapper()
{
using (var StreamReader = new StreamReader(#"D:\Data\Projects\dictUnitMapper.csv"))
{
using (var CsvReader = new CsvReader(StreamReader, CultureInfo.InvariantCulture))
{
var records = CsvReader.GetRecords<varMapper>().ToList();
foreach (var item in records)
{
if (item.name != "#N/A" && item.priority != 0)
{
LineItems lineItem = new LineItems();
lineItem.variableName = item.Items;
lineItem.variableUnit = item.Unit;
lineItem.variableGrowthCheck = item.growth;
lineItem.variableAVGCheck = item.avg;
lineItem.variableSVCheck = item.svData;
lineItem.longName = item.name;
lineItem.priority = item.priority;
}
}
}
}
}
public class LineItems
{
public string variableName;
public string variableUnit;
public bool variableGrowthCheck;
public bool variableAVGCheck;
public bool variableSVCheck;
public string longName;
public int priority;
}
public class varMapper
{
public string Items { get; set; }
public string Unit { get; set; }
public bool growth { get; set; }
public bool avg { get; set; }
public bool svData { get; set; }
public string name { get; set; }
public int priority { get; set; }
}
You should write your method to return a list.
public List<LineItems> GetMapper()
{
using (var StreamReader = new StreamReader(#"D:\Data\Projects\dictUnitMapper.csv"))
{
using (var CsvReader = new CsvHelper.CsvReader(StreamReader, CultureInfo.InvariantCulture))
{
return
CsvReader
.GetRecords<varMapper>()
.Where(item => item.name != "#N/A")
.Where(item => item.priority != 0)
.Select(item => new LineItems()
{
variableName = item.Items,
variableUnit = item.Unit,
variableGrowthCheck = item.growth,
variableAVGCheck = item.avg,
variableSVCheck = item.svData,
longName = item.name,
priority = item.priority,
})
.ToList();
}
}
}
Here's an alternative syntax for building the return value:
return
(
from item in CsvReader.GetRecords<varMapper>()
where item.name != "#N/A"
where item.priority != 0
select new LineItems()
{
variableName = item.Items,
variableUnit = item.Unit,
variableGrowthCheck = item.growth,
variableAVGCheck = item.avg,
variableSVCheck = item.svData,
longName = item.name,
priority = item.priority,
}
).ToList();

MVC None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'

When I try to run MVC I get the following error:
None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'A105004P.Controllers.AssessPersonController' can be invoked with the available services and parameters:
Cannot resolve parameter 'Library.Interface.IAssessPerson AssessPerson' of constructor 'Void .ctor(Library.Interface.IAssessPerson)'.
Here are the relevant files:
ISYM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library.Interface
{
public interface ISYM
{
int id { get; set; }
string ass_name { get; set; }
string unitname { get; set; }
string jobtitle { get; set; }
string phone { get; set; }
string faxphone { get; set; }
string email { get; set; }
string gender { get; set; }
string servicestate { get; set; }
string highestedu { get; set; }
string mainexp { get; set; }
string address { get; set; }
string joinyears { get; set; }
string picfile { get; set; }
string memo { get; set; }
bool enable { get; set; }
string creuser { get; set; }
System.DateTime credate { get; set; }
string edituser { get; set; }
System.DateTime editdate { get; set; }
string tel { get; set; }
void add();
void edit();
void delete();
//IQueryable<ISYM> GetAll();
IList<ISYM> getDataList();
ISYM getSYMId(int? RoleId);
}
}
SYMController
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using FUN2012.Models;
using Library.EFClass;
using Library.Interface;
using Model;
namespace FUN2012.Controllers
{
public class SYMController : Controller
{
ISYM _ap;
public SYMController(ISYM SYM)
{
_ap = SYM;
}
// GET: SYM
public ActionResult Index()
{
SYMViewModel SYM = new SYMViewModel();
IList<ISYM> list = _ap.getDataList();
var query = (from item in list
select new SYMViewModel
{
編號 = item.id,
委員姓名 = item.ass_name,
性別 = item.gender,
機關名稱 = item.unitname,
職稱 = item.jobtitle,
在職情形 = item.servicestate,
連絡電話 = item.phone
}).ToList();
return View(query);
}
[HttpPost]
public ActionResult Index(string search)
{
IList<ISYM> list = _ap.getDataList();
var query = (from item in list
select new SYMViewModel
{
編號 = item.id,
委員姓名 = item.ass_name,
性別 = item.gender,
機關名稱 = item.unitname,
職稱 = item.jobtitle,
在職情形 = item.servicestate,
連絡電話 = item.phone
});
query = query.Where(a => a.委員姓名.Contains(search)).ToList();
return View(query);
}
public ActionResult Details(int id)
{
var IAP = _ap.getDataList();
SYMViewModel APVM = new SYMViewModel();
APVM.編號 = _ap.id;
APVM.委員姓名 = _ap.ass_name;
APVM.機關名稱 = _ap.unitname;
APVM.性別 = _ap.gender;
APVM.職稱 = _ap.jobtitle;
APVM.在職情形 = _ap.servicestate;
APVM.連絡電話 = _ap.phone;
return View(APVM);
}
private void checkNull(SYM item)
{
if (string.IsNullOrEmpty(item.ass_name)) this.ModelState.AddModelError("", "請輸入委員姓名");
if (string.IsNullOrEmpty(item.phone) && string.IsNullOrEmpty(item.tel)) this.ModelState.AddModelError("", "請輸入手機或市話");
if (!string.IsNullOrEmpty(item.phone)) { if (item.phone.Length > 50) this.ModelState.AddModelError("", "手機輸入文字過長,請小於50個字"); }
if (!string.IsNullOrEmpty(item.tel)) { if (item.tel.Length > 50) this.ModelState.AddModelError("", "市話輸入文字過長,請小於50個字"); }
}
public ActionResult returnIndex()
{
return RedirectToAction("Index");
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create([Bind(Include = "編號,委員姓名,機關名稱,性別,職稱,在職情形,連絡電話")] SYMViewModel apvm)
{
_ap.id = apvm.編號;
_ap.ass_name = apvm.委員姓名;
_ap.unitname = apvm.機關名稱;
_ap.gender = apvm.性別;
_ap.jobtitle = apvm.職稱;
_ap.servicestate = apvm.在職情形;
_ap.phone = apvm.連絡電話;
_ap.add();
return RedirectToAction("Index");
}
...
How to fix it?Thank you.
The problem is fixed. Here is Answer below:
public class SYMController : Controller
{
ISYM _ap;
IttaessData _ad;
public SYMController()
{
_ap = new LISYM();
_ad = new LIttaessData();
}
public int pageSize = 15;
public ActionResult Index(int? page, string name)
{
IList<ISYM> list = _ap.getDataList();
var query = (from item in list
select new SYMViewModel
{
id = item.id,
tta_name = item.tta_name,
gender = item.gender,
unitname = item.unitname,
jobtitle = item.jobtitle,
servicestate = item.servicestate,
phone = item.phone,
enable=item.enable
}).ToList();
foreach (var item in query)
{
item.tta_name = item.tta_name == null ? "" : item.tta_name;
}
if (!string.IsNullOrEmpty(name))
{
query = query.Where(a => a.tta_name.Contains(name)).ToList();
}
query = query.Where(a => a.enable==true).ToList();
var result = query
.OrderByDescending(x => x.tta_name)
.ThenBy(x => x.tta_name).ToPagedList(page ?? 1, pageSize);
var num = query.Count();
ViewBag.pageSize = pageSize;
ViewBag.page = page;
ViewBag.num = num;
ViewBag.count = query.Count();
ViewBag.name = name;
return View(result);
}
public ActionResult Detail(int id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SYMViewModel APVM = new SYMViewModel();
ISYM IA = _ap.getSYMId(id);
getFile(IA.picfile, IA.id);
IList<IttaessData> list = _ad.getDataList();
var ttaessdata = (from AD
Thank you.

get correct json output from c# class

Please check from Json output i wanted using JavaScriptSerializer. Then check class helper i created using json2csharp.com. Problem is in controller. I am not getting correct output as per my required Jason. I am doing correct in controller? Where the problem can be? Please ask question if you want to know something specific, sorry its hard to describe more clearly.
Helper Class Code:
public class ItemsFromFile
{
public string ASIN { get; set; }
public string Title { get; set; }
public List<Product> products { get; set; }
}
public class ItemsDeatails
{
public List<ItemsFromFile> ItemsFromFile { get; set; }
}
public class File
{
public string nameLocator { get; set; }
public ItemsDeatails itemsDeatails { get; set; }
}
public class RootObject
{
public string Token { get; set; }
public File file { get; set; }
}
Controller code:
if (type == "Salefreaks")
{
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var ItemsFromFile = new ItemsFromFile()
{
products = new List<Product>()
};
var ItemsDeatails = new ItemsDeatails()
{
};
var File = new File()
{
nameLocator = "testimport1"
};
var RootObject = new RootObject()
{
Token = token
};
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems)
{
ItemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
var json = new JavaScriptSerializer().Serialize(RootObject);
}
Required Json Output code:
{
"Token": "7f3099b0-36b1",
"file": {
"nameLocator": "testimport1",
"itemsDeatails": {
"ItemsFromFile": [
{
"ASIN": "B011KVFT9Y",
"Title": "Disney Batman Durable Party Beach Outdoor Adventure Camp Chair w/ Storage Bag"
},
{
"ASIN": "B01D4KRBW2",
"Title": "High Quality Diy Oil Painting Paint Number Kit Theme-Romantic Street A Frameless"
}
]
}
}
}
You can initialize internal objects in the code in the constructor as well.
public class RootObject
{
public string Token { get; set; }
public File file { get; set; }
}
public class File
{
public File()
{
this.itemsDeatails = new ItemsDeatails();
}
public string nameLocator { get; set; }
public ItemsDeatails itemsDeatails { get; set; }
}
public class ItemsDeatails
{
public ItemsDeatails(){
this.ItemsFromFile = new List<ItemsFromFile>();
}
public List<ItemsFromFile> ItemsFromFile { get; set; }
}
public class ItemsFromFile
{
public ItemsFromFile(){
this.products = new List<Product>();
}
public List<Product> products { get; set; }
}
public class Product {
public string ASIN { get; set; }
public string Title { get; set; }
}
Initialize your items properly. And create Root Object from the ground up.
Populate the internal classes first and then later ones.
var itemDetails = new ItemsDeatails();
itemDetails.ItemsFromFile = new ItemsFromFile();
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems)
{
itemDetails.ItemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
var fl = new File(){
nameLocator = "testimport1",
itemsDeatails = itemDetails
}
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var root = new RootObject()
{
Token = token,
file = fl
}
var json = new JavaScriptSerializer().Serialize(root);
Ensure that all your objects are assigned appropriately.
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var RootObject = new RootObject() {
Token = token,
file = new File() {
nameLocator = "testimport1",
itemsDeatails = new ItemsDeatails() {
ItemsFromFile = new List<ItemsFromFile>()
}
}
};
var itemsFromFile = new ItemsFromFile();
itemsFromFile.products = new List<Product>();
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems) {
itemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
RootObject.file.itemsDeatails.ItemsFromFile.Add(itemsFromFile);
var json = new JavaScriptSerializer().Serialize(RootObject);
That being said, it appears that you do not need the list of products inside of the ItemsFromFile class. This definition likely makes more sense:
public class ItemsFromFile {
public string ASIN { get; set; }
public string Title { get; set; }
}
Then your code would be something like this:
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var RootObject = new RootObject() {
Token = token,
file = new File() {
nameLocator = "testimport1",
itemsDeatails = new ItemsDeatails() {
ItemsFromFile = new List<ItemsFromFile>()
}
}
};
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems) {
RootObject.file.itemsDeatails.ItemsFromFile.Add(new ItemsFromFile { ASIN = item.ASIN, Title = item.EbayTitle });
}

Assign Value in List using lambda expression

I have following classes:
public class ProviderQualificationTimeViewModel
{
public string SessionId { get; set; }
public List<ProviderQualificationDetail> ProviderQualificationDetails { get; set; }
}
public class ProviderQualificationDetail
{
public string ProviderName { get; set; }
public string ProviderQualificationTime { get; set; }
public string TotalServiceableOffers { get; set; }
}
Basically, I want to create a new object if condition is true else I want to update ProviderQualificationDetail.ProviderQualificationTime where ProviderQualificationDetail.ProviderName == providerName
Is it possible using lambda expression?
List<ProviderQualificationDetail> providerQualificationDetail = new List<ProviderQualificationDetail>();
foreach (ProviderModel providers in allProviders)
{
if(!providerQualificationDetail.Any(p=>p.ProviderName.Contains(providerName)))
{
ProviderQualificationDetail ProviderQualificationDetail = new ProviderQualificationDetail();
ProviderQualificationDetail.ProviderName = providerName;
ProviderQualificationDetail.ProviderQualificationTime = Math.Round(processingTime).ToString();
ProviderQualificationDetail.TotalServiceableOffers = "Not serviceable";
providerQualificationDetail.Add(ProviderQualificationDetail);
}
else
{
//Lambda expression here
}
}
like this in else part:
foreach (var item in providerQualificationDetail.Where(x => x.ProviderName== providerName))
{
item.ProviderQualificationTime = Math.Round(processingTime).ToString();
}
Or
providerQualificationDetail.Where(x => x.ProviderName == ProviderName).Select(c =>
{
c.ProviderQualificationTime = "new time ";
return providerQualificationDetail;
}).ToList();
Or
providerQualificationDetail.ForEach(x =>
{
if(x.ProviderName == ProviderName)
x.ProviderQualificationTime = "new time";
});
Try this....
List<ProviderQualificationDetail> providerQualificationDetail = new List<ProviderQualificationDetail>();
foreach (ProviderModel providers in allProviders)
{
if(!providerQualificationDetail.Any(p=>p.ProviderName.Contains(providerName)))
{
ProviderQualificationDetail ProviderQualificationDetail = new ProviderQualificationDetail();
ProviderQualificationDetail.ProviderName = providerName;
ProviderQualificationDetail.ProviderQualificationTime = Math.Round(processingTime).ToString();
ProviderQualificationDetail.TotalServiceableOffers = "Not serviceable";
providerQualificationDetail.Add(ProviderQualificationDetail);
}
else
{
var qualificationDetail = providerQualificationDetail.SingleOrDefault(p => p.ProviderName.Equals(providerName));
//Assing your values here
//example;
qualificationDetail.ProviderName = NewProviderName.ToString();
providerQualificationDetail.SaveChanges();
}
}

How to set up a "Details" page when parsing from XML file in ASP.NET MVC

I have an MVC VS2013 project querying an XML document.
The index action on my controller returns a list of Restaurants, and I need to be able to click the individual restaurants and open a details page which will show the respective properties of that Restaurant.
In previous projects querying from a sql database I would just call the db context, for example
Restaurant restaurant = db.Restaurants.Find(id);
but I am uncertain what the XML querying equivalent is.
Here is what I have so far.
Model:
[XmlRoot("EstablishmentCollection")]
public class Restaurant
{
[Key]
[XmlElement("FHRSID")]
public int? FHRSID { get; set; }
[XmlElement("BusinessName")]
public string BusinessName { get; set; }
[XmlElement("RatingValue")]
public int? RatingValue { get; set; }
[XmlElement("Hygiene")]
public int? HygieneScore { get; set; }
}
Controller:
public ActionResult Index()
{
IQueryable<Restaurant> Res = null;
try
{
var qy = xmlDoc.Descendants("EstablishmentDetail").Select(n => new Restaurant()
{
FHRSID = (int)n.Element("FHRSID"),
BusinessName = n.Element("BusinessName").Value,
RatingValue = RValue(n),
HygieneScore = HScores(n)
});
Res = qy.AsQueryable();
}
catch (Exception ex)
{
string message;
message = ex.Message.ToString();
return View(message);
}
return View(Res);
}
public ActionResult Details (int? id)
{
try
{
var qy = xmlDoc.Descendants("EstablishmentDetail").Select(n => new Restaurant()
{
FHRSID = (int)n.Element("FHRSID"),
BusinessName = n.Element("BusinessName").Value,
RatingValue = RValue(n),
HygieneScore = HScores(n)
});
//What goes here???
}
catch (Exception ex)
{
string message;
message = ex.Message.ToString();
return View(message);
}
return View();
}
Details View:
#model WebApplication3.Models.Restaurant
<h2>Details</h2>
<h6>#Model.FHRSID</h6>
<h6>#Model.BusinessName</h6>
<h6>#Model.HygieneScore</h6>
<h6>#Model.RatingValue</h6>
EDIT:
I have been working on it, is something like the below heading in the right direction?
(Controller)
public ActionResult Details (int? id)
{
var qy = xmlDoc.Descendants("EstablishmentDetail").Select(n => new Restaurant()
{
FHRSID = (int)n.Element("FHRSID"),
BusinessName = n.Element("BusinessName").Value,
RatingValue = RValue(n),
HygieneScore = HScores(n)
}).ToList();
var query = from x in qy
where x.FHRSID == id
select new Restaurant();
return View(query);
}
Problem with the above is that I am having issues correctly sending the query to the view
var r = xmlDoc.Descendants("EstablishmentDetail")
.Select(n => new Restaurant()
{
FHRSID = (int)n.Element("FHRSID"),
BusinessName = n.Element("BusinessName").Value,
RatingValue = RValue(n),
HygieneScore = HScores(n)
})
.Single(r => r.FHRSID == id);
Single, SignleOrDefault, First, FirstOrDefault returns an element from a collection.

Categories

Resources