MVC 4 Paging Searching - asp.net-mvc

I have applied search method in my project but , I have also Action index()
and getting erorr. (The current request for action 'Index' on controller type 'AdultLiteracyTeachersController' is ambiguous between the following action methods:)
public ViewResult Index(string searchstring, string currentFilter, int? page)
{
if (searchstring != null)
{
page = 1;
}
else
{
searchstring = currentFilter;
}
ViewBag.CurrentFilter = searchstring;
var teachers = from r in db.AdulLiteracyTeachers select r;
if (!string.IsNullOrEmpty(searchstring))
{
teachers = teachers.Where(r => r.ALTName.ToUpper().Contains(searchstring.ToUpper()));
}
teachers = teachers.OrderBy(r => r.ALTName);
int pagesize = 10;
int pageNo = (page ?? 1);
return View(teachers.ToPagedList(pageNo, pagesize));
}
The other ActionResult.index()
public ActionResult Index()
{
var adulliteracyteachers = db.AdulLiteracyTeachers.Include(a => a.District);
return View(adulliteracyteachers.ToList());
}
Action result is used for calling all data how can I aplly in single index ?

Combine them:
public ViewResult Index(string searchstring, string currentFilter, int? page)
{
if (searchString == null && currentFilter == null && !page.HasValue)
{
// No parameters
var adulliteracyteachers = db.AdulLiteracyTeachers.Include(a => a.District);
return View(adulliteracyteachers.ToList());
}
// Regular code here down
if (searchstring != null)
{
page = 1;
}
else
{
searchstring = currentFilter;
}
ViewBag.CurrentFilter = searchstring;
var teachers = from r in db.AdulLiteracyTeachers select r;
if (!string.IsNullOrEmpty(searchstring))
{
teachers = teachers.Where(r => r.ALTName.ToUpper().Contains(searchstring.ToUpper()));
}
teachers = teachers.OrderBy(r => r.ALTName);
int pagesize = 10;
int pageNo = (page ?? 1);
return View(teachers.ToPagedList(pageNo, pagesize));
}

Related

asp.net mvc core A second operation was started on the context before the first operation is completed

I am using this code for authorization on controllers.
with [Authorize(Policy = "CustomRole")]
The thing happened that after 3 or 4 request it fails with
A second operation started on this context before a previous operation completed
public class CustomRoleRequirement : AuthorizationHandler<CustomRoleRequirement>, IAuthorizationRequirement
{
public CMSContext _context = new CMSContext();
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRoleRequirement requirement)
{
var routeobj = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
var c = routeobj.RouteData.Values.Values.ToList();
var keys = routeobj.RouteData.Values.Keys.ToList();
string area = "";
string id = "";
string controller = "";
string action = "";
string module = "";
foreach (var item in keys)
{
if (item=="area")
{
int indexs = keys.FindIndex(cc => cc == "area");
area = c[indexs].ToString();
}
else if (item == "id")
{
int indexs = keys.FindIndex(cc => cc == "id");
id = c[indexs].ToString();
}
else if (item == "controller")
{
int indexs = keys.FindIndex(cc => cc == "controller");
controller = c[indexs].ToString();
}
else if (item == "module")
{
int indexs = keys.FindIndex(cc => cc == "module");
module = c[indexs].ToString();
}
else if (item == "action")
{
int indexs = keys.FindIndex(cc => cc == "action");
action = c[indexs].ToString();
}
}
string modulelink = controller;
if (!string.IsNullOrEmpty(module))
{
modulelink = modulelink + "/" + module;
}
List<string> Roles = new List<string>();
int UserId = Auth.UserID;
string UserName = Auth.UserName;
if (UserName == "superadmin")
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
// apparently the error occurred here
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
if (moduleobj != null)
{ // 69 role is assessing news module
//60 role is accessing page module
var RolesModulesobj = _context.AppRolesModules.FirstOrDefault(q => q.ModuleId == moduleobj.ModuleId && q.RolesId == Auth.RoleId);
if (RolesModulesobj != null)
{
string permissionsobj = RolesModulesobj.Permissions;
List<string> PermissionsListobj = permissionsobj.Split(',').Select(x => x.Trim()).ToList();
var FindFullAccess = PermissionsListobj.FirstOrDefault(q => q.Contains("FullAccess:true"));
if (FindFullAccess != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
var abc = PermissionsListobj.FirstOrDefault(q => q.Contains(action + ":true"));
if (abc != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
context.Fail();
return Task.CompletedTask;
}
}
}
}
}
The error occurred at this line above
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
How can I make task wait before the second operation started in the method above?
You can't use a singleton DB context. You either create one each time you need one or you pool them.

Sorting Details Page MVC

I cant figured out how perform sort in a details page. I have a classic page with list of order and for each row i have a actionlink to return details view of that order.
i try this
public ActionResult Details(int? anno,int? nr, string centro, string sortOrder)
{
ViewBag.Codice = String.IsNullOrEmpty(sortOrder) ? "Articolo_desc" : "";
if (anno == null && nr == null && string.IsNullOrEmpty(centro))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
else
{
string s = "anno=" + Request.QueryString["anno"] + "&nr=" + Request.QueryString["nr"] + "&centro=" + Request.QueryString["centro"];
ViewBag.search = s.Replace("search=", "").Replace("%3D", "=");
}
var righe = from d in db.DETAILS
where d.Anno == anno && d.Num == nr && d.Centro == centro
select new DetailsOrdersView
{
Articolo = r.Codice,
...
};
if (righe == null)
return HttpNotFound();
switch(sortOrder)
{
case "Articolo_desc":
righe = righe.OrderByDescending(i => i.Articolo);
break;
default:
righe = righe.OrderBy(i => i.Articolo);
break;
}
return View(righe);
}
}
and in details view
#Html.ActionLink("codice","Details", new { sortOrder = ViewBag.Codice, ViewBag.search })
but i on sorting I get bad request and this is the route
Orders/Details?sortOrder=Articolo_desc&search=anno%3D2017%26nr%3D6%26centro%3D1
#Html.ActionLink("codice", "Details", new { sortOrder = ViewBag.Codice, anno = ViewBag.Anno, centro = ViewBag.Centro , nr= ViewBag.Numero })
i solved as above

Using the generic type 'PagedList.StaticPagedList<T>' requires 1 type arguments

I am working on user roles using Asp.net MVC. I am stuck while working on Admin section. I have mentioned one question above and the second question is similar which is Using the generic type 'System.Collections.Generic.List' requires 1 type arguments
Here is my code.
public ActionResult Index(string searchStringUserNameOrEmail, string currentFilter, int? page)
{
try
{
int intPage = 1;
int intPageSize = 5;
int intTotalPageCount = 0;
if (searchStringUserNameOrEmail != null)
{
intPage = 1;
}
else
{
if (currentFilter != null)
{
searchStringUserNameOrEmail = currentFilter;
intPage = page ?? 1;
}
else
{
searchStringUserNameOrEmail = "";
intPage = page ?? 1;
}
}
ViewBag.CurrentFilter = searchStringUserNameOrEmail;
List col_UserDTO = new List();
int intSkip = (intPage - 1) * intPageSize;
intTotalPageCount = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.Count();
var result = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.OrderBy(x => x.UserName)
.Skip(intSkip)
.Take(intPageSize)
.ToList();
foreach (var item in result)
{
ExpandedUserDTO objUserDTO = new ExpandedUserDTO();
objUserDTO.UserName = item.UserName;
objUserDTO.Email = item.Email;
objUserDTO.LockoutEndDateUtc = item.LockoutEndDateUtc;
col_UserDTO.Add(objUserDTO);
}
// Set the number of pages
// Error appears here
var _UserDTOAsIPagedList =
new StaticPagedList
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
return View(_UserDTOAsIPagedList);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error: " + ex);
List col_UserDTO = new List(); // Error appears here
return View(col_UserDTO.ToPagedList(1, 25));
}
}
#endregion
`
StaticPagedList is generic. You need to supply the type of collection(for col_UserDTO), in your case List:
var _UserDTOAsIPagedList =
new StaticPagedList<List<ExpandedUserDTO>>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
See http://www.programering.com/a/MTN2gDNwATM.html
You may need to change List col_UserDTO references to List<ExpandedUserDTO> col_UserDTO
Use this instead
var _UserDTOAsIPagedList =
new StaticPagedList<ExpandedUserDTO>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);

uBlogsy (webforms) PostService showing no posts on landing page

I'm using uBlogsy WebForms 3.0.2 on Umbraco 6.1.5...
And the posts on the landing page are not showing up.
The function PostService.Instance.GetPosts is returning 0 posts, even though there are posts in the correct location.
I still get 0 posts when I try to substitute this:
var posts = PostService.Instance
.GetPosts(
IPublishedContentHelper.GetNode((int)Model.Id)
).ToIPublishedContent(true);
int postCount = posts.Count();
Would anyone know why the PostService isn't working? Or, what is going on?
I had same problem couple of times with Ublogsy. So I decided to write my own codes as below:
(Its a bit long)
// get tag, label, or author from query string
var tag = Request.QueryString["tag"] ?? "";
var label = Request.QueryString["label"] ?? "";
var author = Request.QueryString["author"] ?? "";
var searchTerm = Request.QueryString["search"] ?? "";
var commenter = Request.QueryString["commenter"] ?? "";
int page = int.TryParse(Request.QueryString["page"], out page) ? page : 1;
var year = Request.QueryString["year"] ?? "";
var month = Request.QueryString["month"] ?? "";
var day = Request.QueryString["day"] ?? "";
int postCount;
IEnumerable<IPublishedContent> posts = new BlockingCollection<IPublishedContent>();
var filterResults = this.FilterAgainstPosts(this.Model.Content, tag, label, author, searchTerm, commenter, year, month);
if (filterResults != null)
{
posts = Enumerable.Take(filterResults.Skip((page - 1) * itemsPerPage), itemsPerPage);
}
#RenderForLanding(posts)
And my FilterAgainstPosts method is as follow:
#functions
{
private IEnumerable<IPublishedContent> FilterAgainstPosts(IPublishedContent landing, string tag, string label, string author, string searchTerm, string commenter, string year, string month)
{
IEnumerable<IPublishedContent> filteredPosts = landing.DescendantsOrSelf("uBlogsyPost").Where(x => x.GetProperty("umbracoNaviHide").Value.ToString() != "1");
if (!String.IsNullOrEmpty(searchTerm))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterAgainstTerm(i, searchTerm));
}
if (!String.IsNullOrEmpty(tag))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponTag(i, i.GetProperty("uBlogsyPostTags").Value.ToString(), tag));
}
if (!String.IsNullOrEmpty(label))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponLabel(i, i.GetProperty("uBlogsyPostLabels").Value.ToString(), label));
}
if (!String.IsNullOrEmpty(author))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponAuthor(i, i.GetProperty("uBlogsyPostAuthor").Value.ToString(), author));
}
//
//TODO: Coomenter search needs to added
//
if (!string.IsNullOrEmpty(year))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponYear(i, i.GetProperty("uBlogsyPostDate").Value.ToString(), year));
}
if (!string.IsNullOrEmpty(month))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponMonth(i, i.GetProperty("uBlogsyPostDate").Value.ToString(), month));
}
return filteredPosts.WhereNotNull();
}
private IPublishedContent FilterUponMonth(IPublishedContent currentNode, string postDate, string month)
{
DateTime postedDate;
if (DateTime.TryParse(postDate, out postedDate) && postedDate.Month.ToString() == month) return currentNode;
return null;
}
private IPublishedContent FilterUponYear(IPublishedContent currentNode, string postDate, string year)
{
DateTime postedDate;
if (DateTime.TryParse(postDate, out postedDate) && postedDate.Year.ToString() == year) return currentNode;
return null;
}
private IPublishedContent FilterUponAuthor(IPublishedContent currentNode, string authorId, string author)
{
if (String.IsNullOrEmpty(authorId)) return null;
//Loads relevant node
int authorNodeId = -1;
if (!Int32.TryParse(authorId, out authorNodeId)) return null;
Node authorNode = new Node(authorNodeId);
//Trims the author name and search for given name
if (authorNode.GetProperty("uBlogsyAuthorName") != null && authorNode.GetProperty("uBlogsyAuthorName").Value.ToUpper().Trim().Contains(author.ToUpper())) return currentNode;
return null;
}
private Boolean FilterUponAuthor(string authorId, string author)
{
if (String.IsNullOrEmpty(authorId)) return false;
int authorNodeId = -1;
if (!Int32.TryParse(authorId, out authorNodeId)) return false;
Node authorNode = new Node(authorNodeId);
if (authorNode.GetProperty("uBlogsyAuthorName") != null && authorNode.GetProperty("uBlogsyAuthorName").Value.ToUpper().Trim().Contains(author.ToUpper())) return true;
return false;
}
private Boolean FilterUponCategories(string categoryIds, string category)
{
if (String.IsNullOrEmpty(categoryIds)) return false;
int categoryNodeID = -1;
foreach (string catID in categoryIds.Split(','))
{
if (!Int32.TryParse(catID, out categoryNodeID)) continue;
Node categoryNode = new Node(categoryNodeID);
if (categoryNode.GetProperty("uBlogsyLabelName") != null && categoryNode.GetProperty("uBlogsyLabelName").Value.ToUpper().Trim().Contains(category.ToUpper())) return true;
}
return false;
}
private Boolean FilterUponTags(string tagIds, string tag)
{
if (String.IsNullOrEmpty(tagIds)) return false;
int tagNodeID = -1;
foreach (string tagID in tagIds.Split(','))
{
if (!Int32.TryParse(tagID, out tagNodeID)) continue;
Node tagNode = new Node(tagNodeID);
if (tagNode.GetProperty("uTagsyTagName") != null && tagNode.GetProperty("uTagsyTagName").Value.ToUpper().Trim().Contains(tag.ToUpper())) return true;
}
return false;
}
private IPublishedContent FilterUponLabel(IPublishedContent currentNode, string nodeIDs, string label)
{
if (String.IsNullOrEmpty(nodeIDs)) return null;
foreach (string nodeId in nodeIDs.Split(','))
{
int labelNodeId = -1;
if (!Int32.TryParse(nodeId, out labelNodeId))
continue;
//Loads relevant node
Node labelNode = new Node(labelNodeId);
if (labelNode.GetProperty("uBlogsyLabelName") != null && labelNode.GetProperty("uBlogsyLabelName").Value.ToUpper().Trim().Contains(label.ToUpper())) return currentNode;
}
return null;
}
private IPublishedContent FilterAgainstTerm(IPublishedContent currentNode, string searchTerm)
{
if (String.IsNullOrEmpty(searchTerm)) return currentNode;
if (currentNode.GetProperty("uBlogsyContentTitle").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsyContentSummary").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsyContentBody").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsySeoKeywords").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsySeoDescription").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsyNavigationTitle").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
FilterUponAuthor(currentNode.GetProperty("uBlogsyPostAuthor").Value.ToString(), searchTerm.ToUpper()) ||
FilterUponCategories(currentNode.GetProperty("uBlogsyPostLabels").Value.ToString(), searchTerm.ToUpper()) ||
FilterUponTags(currentNode.GetProperty("uBlogsyPostTags").Value.ToString(), searchTerm.ToUpper())
)
return currentNode;
return null;
}
private IPublishedContent FilterUponTag(IPublishedContent currentNode, string nodeIDs, string tag)
{
if (String.IsNullOrEmpty(nodeIDs)) return null;
foreach (string nodeId in nodeIDs.Split(','))
{
int tagNodeId = -1;
if (!Int32.TryParse(nodeId, out tagNodeId))
continue;
// Loads relevant TagNode
Node tagNode = new Node(tagNodeId);
if (tagNode.GetProperty("uTagsyTagName") != null && tagNode.GetProperty("uTagsyTagName").Value.ToUpper().Contains(tag.ToUpper())) return currentNode;
}
return null;
}
}

Pass object to another action of ASP.net MVC 2

I have one view that used to display the result of my search item. This is its controller :
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
string empType = frm["empType"].ToString();
int totalMonth = 3;
int mon = DateTime.Now.Month;
int yr = DateTime.Now.Year;
string Curdate = mon + "/" + yr;
DateTime date = new DateTime();
var result = (from e in context.tblEmployees
join p in context.tblEmployee_Position on e.PositionIDF equals p.PositionID
select new EvaluateEmployee
{
ID = e.Code,
IDCard = e.IDCard,
Name = e.NameEng,
DOB = e.DOB,
Position = p.Position,
Sex = e.Sex,
StartDate = e.StartDate
}).ToList();
result = result.Where(((s => mon - int.Parse(s.StartDate.Substring(3, 2).ToString()) == totalMonth && yr -int.Parse(s.StartDate.Substring(6, 4).ToString()) == totalYear))).ToList();
ViewData["EmployeeType"] = result;
return View();
}
I displayed the content in the view by looping ViewData["EmployeeType"] and I also included one Print label :
<script language="javascript" type="text/javascript">
function printChart() {
var URL = "EvaluatingReport";
var W = window.open(URL);
W.window.print();
}
function printPage(sURL) {
var oHiddFrame = document.createElement("iframe");
oHiddFrame.src = sURL;
oHiddFrame.style.visibility = "hidden";
oHiddFrame.style.position = "fixed";
oHiddFrame.style.right = "0";
oHiddFrame.style.bottom = "0";
document.body.appendChild(oHiddFrame);
oHiddFrame.contentWindow.onload = oHiddFrame.contentWindow.print;
oHiddFrame.contentWindow.onafterprint = function () {
document.body.removeChild(oHiddFrame); };
}
</script>
<span onclick="printPage('/Report/PrintEvaluatingReport');" style="cursor:pointer;text-decoration:none;color:#0000ff;">
<img src="../../Content/images/Print.png" width="35px;" alt="print" style="position:relative;top:6px;"/>
Print Report
</span>
I used function printPage('/Report/PrintEvaluatingReport') to load the print dialog with the action PrintEvaluatingReport. So I want to take the object that I have in EvaluatingReport to the action PrintEvaluatingReport.
Could anyone tell me how could I do that?
Thanks in advanced.
You could use TempData["EmployeeType"]
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
string empType = frm["empType"].ToString();
int totalMonth = 3;
int mon = DateTime.Now.Month;
int yr = DateTime.Now.Year;
string Curdate = mon + "/" + yr;
DateTime date = new DateTime();
var result = (from e in context.tblEmployees
join p in context.tblEmployee_Position on e.PositionIDF equals p.PositionID
select new EvaluateEmployee
{
ID = e.Code,
IDCard = e.IDCard,
Name = e.NameEng,
DOB = e.DOB,
Position = p.Position,
Sex = e.Sex,
StartDate = e.StartDate
}).ToList();
result = result.Where(((s => mon - int.Parse(s.StartDate.Substring(3, 2).ToString()) == totalMonth && yr -int.Parse(s.StartDate.Substring(6, 4).ToString()) == totalYear))).ToList();
ViewData["EmployeeType"] = result;
// Store in TempData to be read by PrintEvaluatingReport
TempData["EmployeeType"] = result;
return View();
}
public ActionResult PrintEvaluatingReport()
{
var employeeType = TempData["EmployeeType"] as EmployeeType;
// do stuff
return View();
}
You can use a session variable for that !!
private EmployeeType Result
{
get { return (EmployeeType)this.Session["Result"]; }
set
{
this.Session["Result"] = value;
}
}
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
.
.
.
// Store in Session
this.Result = result;
return View();
}
public ActionResult PrintEvaluatingReport()
{
var employeeType = this.Result;
.
.
.
}

Resources