uBlogsy (webforms) PostService showing no posts on landing page - umbraco

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;
}
}

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.

EntityState.Modify instead of Delete in my database

I am using AuditTrail for logging but I have problem. I tried this method ;
http://kamoga.net/audit-trail-and-entity-change-tracking-using-entity-framework-dbcontext/
But I don't delete record for delete operations. I have 'IsDeleted' column and set this column true.
If I use EntityState.Modified in my ActionResult, my 'Action' column value set 'U' but I want to set'D' in database.
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
dbContext = new dbContext();
Gallery gallery = dbContext.Gallery.Find(id);
gallery.IsDeleted = true;
dbContext.Entry(gallery).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChanges();
}
My Enum;
public enum AuditActions
{
I,
U,
A
}
AuditTrail.cs ;
public class AuditTrail
{
public int Id { get; set; }
public string TableName { get; set; }
public string UserName { get; set; }
public string Actions { get; set; }
public string OldData { get; set; }
public string NewData { get; set; }
public string ChangedColums { get; set; }
public string TableIdValue { get; set; }
}
AuditFactoryTrail.cs;
public AuditTrail GetAudit(DbEntityEntry entry)
{
AuditTrail audit = new AuditTrail();
audit.UserName = "Current User"; //You can pass the current user as a parameter
audit.TableName = GetTableName(entry);
audit.TableIdValue = GetKeyValue(entry);
//entry is Added
if (entry.State == EntityState.Added)
{
var newValues = new StringBuilder();
SetAddedProperties(entry, newValues);
audit.NewData = newValues.ToString();
audit.Actions = AuditActions.I.ToString();
}
//entry in deleted
else if (entry.State == EntityState.Deleted)
{
var oldValues = new StringBuilder();
SetDeletedProperties(entry, oldValues);
audit.OldData = oldValues.ToString();
audit.Actions = AuditActions.D.ToString();
}
//entry is modified
else if (entry.State == EntityState.Modified)
{
var oldValues = new StringBuilder();
var newValues = new StringBuilder();
SetModifiedProperties(entry, oldValues, newValues);
audit.OldData = oldValues.ToString();
audit.NewData = newValues.ToString();
audit.Actions = AuditActions.U.ToString();
var modifiedProperties = entry.CurrentValues.PropertyNames.Where(propertyName => entry.Property(propertyName).IsModified).ToList();
var properties = string.Join("||", modifiedProperties.ToList());
audit.ChangedColums = properties;
}
return audit;
}
private void SetAddedProperties(DbEntityEntry entry, StringBuilder newData)
{
foreach (var propertyName in entry.CurrentValues.PropertyNames)
{
var newVal = entry.CurrentValues[propertyName];
if (newVal != null)
{
newData.AppendFormat("{0}={1} || ", propertyName, newVal);
}
}
if (newData.Length > 0)
newData = newData.Remove(newData.Length - 3, 3);
}
private void SetDeletedProperties(DbEntityEntry entry, StringBuilder oldData)
{
DbPropertyValues dbValues = entry.GetDatabaseValues();
foreach (var propertyName in dbValues.PropertyNames)
{
var oldVal = dbValues[propertyName];
if (oldVal != null)
{
oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
}
}
if (oldData.Length > 0)
oldData = oldData.Remove(oldData.Length - 3, 3);
}
private void SetModifiedProperties(DbEntityEntry entry, StringBuilder oldData, StringBuilder newData)
{
DbPropertyValues dbValues = entry.GetDatabaseValues();
foreach (var propertyName in entry.OriginalValues.PropertyNames)
{
var oldVal = dbValues[propertyName];
var newVal = entry.CurrentValues[propertyName];
if (oldVal != null && newVal != null && !Equals(oldVal, newVal))
{
newData.AppendFormat("{0}={1} || ", propertyName, newVal);
oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
}
}
if (oldData.Length > 0)
oldData = oldData.Remove(oldData.Length - 3, 3);
if (newData.Length > 0)
newData = newData.Remove(newData.Length - 3, 3);
}
private string GetKeyValue(DbEntityEntry entry)
{
var objectStateEntry = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
string id = "0";
if (objectStateEntry.EntityKey.EntityKeyValues != null)
id = objectStateEntry.EntityKey.EntityKeyValues[0].Value.ToString();
return id;
}
private string GetTableName(DbEntityEntry dbEntry)
{
TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;
string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;
return tableName;
}
private EntityObject CloneEntity(EntityObject obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
EntityObject newObject = (EntityObject)dcSer.ReadObject(memoryStream);
return newObject;
}
}
DbContext.cs;
public override int SaveChanges()
{
var auditFactory = new AuditTrailFactory(this);
var entityList = ChangeTracker.Entries().Where(p =>
p.State == EntityState.Added ||
p.State == EntityState.Deleted ||
p.State == EntityState.Modified ||
!(p.Entity is AuditTrail) ||
p.Entity != null);
entityList.ToList().ForEach(entity =>
{
AuditTrail audit = auditFactory.GetAudit(entity);
AuditTrail.Add(audit);
});
return base.SaveChanges();
}

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

How to send message/notification to browser/client in Kendo Mvc Ajax Bound Grid (confirm update or create) ( by cookies)

how to send notification to client in kendo mvc ajax bound ,
i do not know if this is good way ..
of course you can add ModelState.AddModelError("notification","….msg.")
and …. But it tell to datasource ajax action failed.. So..
Addclass:
public class AjaxErrorMsg
{
public AjaxErrorMsg()
{
CssClass = "gray";
AutoHide = false;
AutoHideDelay = 200;
Kind = "error";
Title = "error";
}
public string Msg { get; set; }
public string Kind { get; set; }
public Boolean AutoHide { get; set; }
public Int32 AutoHideDelay { get; set; }
public string CssClass { get; set; }
public string Title { get; set; }
}
In controller
public void StoreMessageInCookie(string msg, Boolean isError = false, string msgDivClass = "", string preMessage = "", string msgTitle = "")
{
StoreMessageInCookie(new Exception(msg), isError, msgDivClass, preMessage, msgTitle);
}
public void StoreMessageInCookie(Exception ee, Boolean isError = false, string msgDivClass = "", string preMessage = "", string msgTitle = "")
{
List<AjaxErrorMsg> rs;
var js = new JavaScriptSerializer();
if (this.Response.Cookies[Common1.MsgCookie].HasKeys )
{
try
{
rs = js.Deserialize<List<AjaxErrorMsg>>(this.Response.Cookies[Common1.MsgCookie].Value);
}
catch
{
rs = new List<AjaxErrorMsg>();
}
}
else
{
rs = new List<AjaxErrorMsg>();
}
var msg0 = new AjaxErrorMsg();
if (isError)
{
msgDivClass = msgDivClass == "" ? "DivAlarmStyle6 fontMitra" : msgDivClass;
msg0.Kind = "error";
msg0.AutoHide = false;
msg0.Title = "Error";
}
else
{
msg0.Kind = "alert";
msg0.AutoHide = true;
msg0.Title = "Warning";
}
msg0.Title = msgTitle == "" ? msg0.Title : msgTitle;
msg0.Msg = preMessage + cm2.FilterMessageText(ee, IsAdminUser);
if (msgDivClass.Trim() != "")
msg0.Msg = Common1.WrapTextInDivWithClass(msg0.Msg, msgDivClass);
rs.Add(msg0);
this.Response.Cookies.Add(new HttpCookie(Common1.MsgCookie, js.Serialize(rs)));
}
cm2.FilterMessageText is function to remove database object name from error message string ..also include any inner exception message
Then when you what to send message use command
StoreMessageInCookie("Message 1 2 ! ");
And in your MainProject.js
Add all of code below
function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function ReadAnShowCookieForDeliverMessages() {
try {
var listMsg = readCookie("CookieForDeliverMessages")
if (!!listMsg) {
eraseCookie("CookieForDeliverMessages");
ShowAndLogMessageListOfAjaxError($.parseJSON(listMsg));
}
} catch (ee) {
alert(" error in ReadAnShowCookieForDeliverMessages")
}
}
function ShowAndLogMessageListOfAjaxError(ListOfAjaxError) {
if (ListOfAjaxError == undefined)
return;
ListOfAjaxError.forEach(function (AjaxError) {
ShowAndLogMessageByAjaxErrorClass(AjaxError)
})
}
function ShowAndLogMessageByAjaxErrorClass(AjaxError) {
if ((AjaxError != undefined) && (AjaxError.Msg != "")) {
// I used freeow => https://github.com/pjdietz/Freeow
$("#freeow").freeow(AjaxError.Title, AjaxError.Msg, { classes: [AjaxError.CssClass, AjaxError.Kind], autoHide: AjaxError.AutoHide, autoHideDelay: AjaxError.AutoHideDelay });
// LogMsg(AjaxError.Msg, AjaxError.Title); function to log message on client
}
}
$(function () {
MyAjaxSetting();
ReadAnShowCookieForDeliverMessages();
}
function MyAjaxSetting() {
$(document).ajaxComplete(function (o) {
ReadAnShowCookieForDeliverMessages()
});
}

MVC 4 Paging Searching

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));
}

Resources