Paging broken when filtering MVC - c#

I'm trying to get paging to work with multiple searches and sort orders. When I do a search the first page returned is the correct page of the result set but when I use the pagination buttons to select the next page my search no longer factors in and I get all results.
My controller looks like this:
public ActionResult Index(string sortOrder, string searchString, string currentFilter, int? page, string Site, string Name, string Acct, string City, string State, string Address, string Status, string Type)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.AddressSortParm = sortOrder == "Address" ? "addr_desc" : "Address";
ViewBag.SiteSortParm = sortOrder == "Site" ? "site_desc" : "Site";
ViewBag.CitySortParm = sortOrder == "City" ? "city_desc" : "City";
ViewBag.StateSortParm = sortOrder == "State" ? "state_desc" : "State";
if (searchString != null || Site != null || Name != null || Acct != null || City != null || State != null || Address != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var geocodes = from s in db.CFN_Geocodes select s;
if (!String.IsNullOrEmpty(Name))
{
geocodes = geocodes.Where(s => s.NAME.Contains(Name));
}
if (!String.IsNullOrEmpty(Site))
{
geocodes = geocodes.Where(s => s.CFN_SITE.Contains(Site));
}
if (!String.IsNullOrEmpty(Address))
{
geocodes = geocodes.Where(s => s.STREET1.Contains(Address));
}
if (!String.IsNullOrEmpty(City))
{
geocodes = geocodes.Where(s => s.CITY.Contains(City));
}
if (!String.IsNullOrEmpty(State))
{
geocodes = geocodes.Where(s => s.STATE_CODE.Contains(State));
}
if (!String.IsNullOrEmpty(Acct))
{
geocodes = geocodes.Where(s => s.AccountNumber.Contains(Acct));
}
if (!String.IsNullOrEmpty(Status))
{
geocodes = geocodes.Where(s => s.Status.ToString().Contains(Status));
}
if (!String.IsNullOrEmpty(Type))
{
geocodes = geocodes.Where(s => s.SiteType.Contains(Type));
}
switch (sortOrder)
{
case "name_desc":
geocodes = geocodes.OrderByDescending(s => s.NAME);
break;
case "Address":
geocodes = geocodes.OrderBy(s => s.STREET1);
break;
case "addr_desc":
geocodes = geocodes.OrderByDescending(s => s.STREET1);
break;
case "Site":
geocodes = geocodes.OrderBy(s => s.CFN_SITE);
break;
case "site_desc":
geocodes = geocodes.OrderByDescending(s => s.CFN_SITE);
break;
case "City":
geocodes = geocodes.OrderBy(s => s.CITY);
break;
case "city_desc":
geocodes = geocodes.OrderByDescending(s => s.CITY);
break;
case "State":
geocodes = geocodes.OrderBy(s => s.STATE_CODE);
break;
case "state_desc":
geocodes = geocodes.OrderByDescending(s => s.STATE_CODE);
break;
default:
geocodes = geocodes.OrderBy(s => s.NAME);
break;
}
int pageSize = 20;
int pageNumber = (page ?? 1);
return View(geocodes.ToPagedList(pageNumber, pageSize));
}
And my view looks like this:
#model PagedList.IPagedList<Intranet.Models.CardlockSiteMgr.CFN_Geocodes>
#using PagedList.Mvc
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Site Manager";
}
<h2>Site Manager</h2>
<h5>#Html.ActionLink("Add New Site", "Create")</h5>
#using (Html.BeginForm())
{
<table class="table table-responsive table-condensed">
<tr>
<td colspan="6"><h4>Search Sites</h4></td>
</tr>
<tr>
<td>
Site:
</td>
<td>
#Html.TextBox("Site")
</td>
<td>
Account:
</td>
<td>
#Html.TextBox("Acct")
</td>
<td>
Name:
</td>
<td>
#Html.TextBox("Name")
</td>
</tr>
<tr>
<td>
Address:
</td>
<td>
#Html.TextBox("Address")
</td>
<td>
City:
</td>
<td>
#Html.TextBox("City")
</td>
<td>
State:
</td>
<td>
#Html.TextBox("State")
</td>
</tr>
<tr>
<td>
Status:
</td>
<td>
<select name="Status">
<option></option>
<option>Active</option>
<option>Inactive</option>
</select>
</td>
<td>
Type:
</td>
<td>
<select name="Type">
<option></option>
<option>CFN</option>
<option>Fleetwide</option>
</select>
</td>
<td></td>
<td>
<input type="submit" value="Search" />
</td>
</tr>
</table>
}
<table class="table table-responsive table-striped">
<tr>
<th>
#Html.ActionLink("Site", "Index", new { sortOrder = ViewBag.SiteSortParm })
</th>
<th>
#Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm })
</th>
<th>
#Html.ActionLink("Address", "Index", new { sortOrder = ViewBag.AddressSortParm })
</th>
<th>
#Html.ActionLink("City", "Index", new { sortOrder = ViewBag.CitySortParm })
</th>
<th>
#Html.ActionLink("State", "Index", new { sortOrder = ViewBag.StateSortParm })
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CFN_SITE)
</td>
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.STREET1)
</td>
<td>
#Html.DisplayFor(modelItem => item.CITY)
</td>
<td>
#Html.DisplayFor(modelItem => item.STATE_CODE)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.SITE_ID })
</td>
</tr>
}
</table>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
Any ideas on what I'm doing wrong here?

I ended up using session variables, even though it's not the best method.
if (Status != null)
{
System.Web.HttpContext.Current.Session["Status"] = Status;
}
if (System.Web.HttpContext.Current.Session["Status"] != null)
{
Status = System.Web.HttpContext.Current.Session["Status"].ToString();
}
if (Type != null)
{
System.Web.HttpContext.Current.Session["Type"] = Type;
}
if (System.Web.HttpContext.Current.Session["Type"] != null)
{
Type = System.Web.HttpContext.Current.Session["Type"].ToString();
}
if (Name != null)
{
System.Web.HttpContext.Current.Session["Name"] = Name;
}
if (System.Web.HttpContext.Current.Session["Name"] != null)
{
Name = System.Web.HttpContext.Current.Session["Name"].ToString();
}
if (Site != null)
{
System.Web.HttpContext.Current.Session["Site"] = Site;
}
if (System.Web.HttpContext.Current.Session["Site"] != null)
{
Site = System.Web.HttpContext.Current.Session["Site"].ToString();
}
if (Acct != null)
{
System.Web.HttpContext.Current.Session["Acct"] = Acct;
}
if (System.Web.HttpContext.Current.Session["Acct"] != null)
{
Acct = System.Web.HttpContext.Current.Session["Acct"].ToString();
}
if (City != null)
{
System.Web.HttpContext.Current.Session["City"] = City;
}
if (System.Web.HttpContext.Current.Session["City"] != null)
{
City = System.Web.HttpContext.Current.Session["City"].ToString();
}
if (State != null)
{
System.Web.HttpContext.Current.Session["State"] = State;
}
if (System.Web.HttpContext.Current.Session["State"] != null)
{
State = System.Web.HttpContext.Current.Session["State"].ToString();
}
if (Address != null)
{
System.Web.HttpContext.Current.Session["Address"] = Address;
}
if (System.Web.HttpContext.Current.Session["Address"] != null)
{
Address = System.Web.HttpContext.Current.Session["Address"].ToString();
}

Related

C# HTML.Actionlink strange behaviour on server

If someone can help, I would be very thankful.
I'm using C# in VS 2017 for an ASP.net Application.
In a razor view, I have this code:
<div class="text-center" >
<ul class="pagination">
#for (var i = 1; i <= ViewBag.SearchMetaData.SearchNumberOfPages; i++)
{
if (ViewBag.SearchMetaData.SearchCurrentPage == #i)
{
<li class="active"> #Html.ActionLink(#i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", new { id = #i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)</li>
}
else
{
<li> #Html.ActionLink(#i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", "Home", new { id = #i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)</li>
}
}
</ul>
</div>
}
It works great on my development machine. The actionlinks never fail.
However, when I publish to the server, I can click on the links 3 or 4 times and they work. After the 4th time, it is like the variables are forgotten. When I view the page source the links appear to correct. It seems to me something on the server is being reset. Does anyone have any ideas?
Here is more code:
____________EDIT AFTER THIS LINE__________________
Controller:
public ActionResult CI_SequenceBlocks()
{
string strIP = "";
string strSRCHString = "";
string strSRCHstringQry = "";
int intSRCHRequestedPage = 1;
int intSRCHPageSize = 10;
if (TempData["CI_SequenceBlocks_InstitutionProgram"] == null)
{
strIP = "0";
strSRCHString = "";
}
else
{
strIP = TempData["CI_SequenceBlocks_InstitutionProgram"].ToString();
strSRCHString = TempData["CI_SequenceBlocks_SRCHString"]?.ToString() ?? "";
};
ViewData["listInstitutionPrograms"] = new SelectList(MSSQL_CI_Repository.ListInstitutionProgramsForComboBoxes(), "Value", "Text");
ViewData["SelectedInstitutionProgram"] = strIP;
ViewData["inSRCHString"] = strSRCHString;
ViewBag.SRCHString = strSRCHString;
//ViewBag.InstitutionalProgram = strIP;
if (strSRCHString == "") { ViewBag.SRCHDescriptor = "NO_SEARCH_TERM"; } else { ViewBag.SRCHDescriptor = strSRCHString?.ToString() ?? "NO_SEARCH_TERM"; }
if (strSRCHString.Trim() == "")
{
strSRCHstringQry = "rttyghujmgdddh";
}
else
{
strSRCHstringQry = strSRCHString;
}
if(TempData["CI_SequenceBlocks_RequestedPage"] != null)
{
intSRCHRequestedPage = Convert.ToInt32(TempData["CI_SequenceBlocks_RequestedPage"]);
}
vm_CI_SequenceBlocksWithSearchMetaData obj = MSSQL_CI_Repository.ListCI_SequenceBlocksByInstitutionalProgramForFullTextSearch(Convert.ToInt32(strIP), strSRCHstringQry,intSRCHPageSize,intSRCHRequestedPage);
ViewBag.SearchMetaData = obj.SearchMetaData;
var model = obj.lstSequenceBlocks;
return View(model);
}
[HttpPost]
public ActionResult CI_SequenceBlocks_FullTextSearch(FormCollection form)
{
TempData["CI_SequenceBlocks_InstitutionProgram"] = form["HidInstitutionProgram"].ToString();
TempData["CI_SequenceBlocks_SRCHString"] = form["SRCHString"].ToString();
TempData["CI_SequenceBlocks_RequestedPage"] = 1;
return RedirectToActionPermanent("CI_SequenceBlocks");
}
public ActionResult CI_SequenceBlocks_Edit_Form_Handler(int id, string value, int inInstitutionProgramID)
{
TempData["CI_SequenceBlocks_InstitutionProgramID"] = inInstitutionProgramID;
TempData["CI_SequenceBlocks_SequenceBlockID"] = id;
if (value == "Edit_SequenceBlock_ID")
{
return RedirectToAction("CI_SequenceBlock_Edit");
}
else if (value == "Maintain_SequenceBlock_ID")
{
return RedirectToAction("CI_SequenceBlock_Maintain");
}
else
{
TempData["CI_SequenceBlocks_InstitutionProgram"] = inInstitutionProgramID;
return RedirectToAction("CI_SequenceBlocks");
}
}
public ActionResult CI_SequenceBlocks_Pager_Form_Handler(int id, string value, int inInstitutionProgramID)
{
TempData["CI_SequenceBlocks_InstitutionProgram"] = inInstitutionProgramID;
TempData["CI_SequenceBlocks_SRCHString"] = value;
TempData["CI_SequenceBlocks_RequestedPage"] = id;
return RedirectToActionPermanent("CI_SequenceBlocks");
}
[HttpPost]
public ActionResult CI_SequenceBlocks_ProgramChange(FormCollection form)
{
TempData["CI_SequenceBlocks_InstitutionProgram"] = form["SelectedInstitutionProgram"].ToString();
return RedirectToActionPermanent("CI_SequenceBlocks");
}
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{id2}/{id3}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, id2 = UrlParameter.Optional, id3 = UrlParameter.Optional }
);
}
Full Razor Code:
#model IEnumerable<UTCI_Manager.Models.vm_CI_SequenceBlock>
#{
ViewBag.Title = "CI_SequenceBlocks";
}
<h2>CI_SequenceBlocks</h2>
#using (Html.BeginForm("CI_SequenceBlocks_ProgramChange", "Home", FormMethod.Post, new { id = "submitForm" }))
{
#Html.DisplayNameFor(model => model.InstitutionProgramID)
#Html.DropDownList("SelectedInstitutionProgram", (SelectList)ViewData["listInstitutionPrograms"], new { onchange = "this.form.submit();" })
}
#using (Html.BeginForm("CI_Sequenceblocks_FullTextSearch", "Home", FormMethod.Post, new { id = "submitForm" }))
{
if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
{
<div class="input-group">
#Html.Hidden("HidInstitutionProgram", ViewData["SelectedInstitutionProgram"]?.ToString() ?? "0")
#Html.TextBox("SRCHString", ViewData["inSRCHString"].ToString(), new { #class = "form-control", #placeholder = "Search" })
<span class="input-group-btn">
<button class="btn btn-info" type='submit' value="Search">Search</button>
</span>
</div>
}
}
<table class="table table-striped" summary="List of Sequence Blocks">
<tr>
#* <th>
#Html.DisplayNameFor(model => model.SequenceBlockID)
</th>
<th>
#Html.DisplayNameFor(model => model.InstitutionProgramID)
</th>
*#
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.SequenceBlockDescription)
</th>
<th>
#Html.DisplayNameFor(model => model.SequenceBlockRequired)
</th>
#* <th>
#Html.DisplayNameFor(model => model.Minimum)
</th>
<th>
#Html.DisplayNameFor(model => model.Maximum)
</th>
*#
<th>
#Html.DisplayNameFor(model => model.SequenceBlockTimingMethod)
</th>
<th>
#Html.DisplayNameFor(model => model.Duration)
</th>
<th>
#Html.DisplayNameFor(model => model.StartDate)
</th>
<th>
#Html.DisplayNameFor(model => model.EndDate)
</th>
<th>
#Html.DisplayNameFor(model => model.ClerkshipModel)
</th>
<th>
#using (Html.BeginForm("CI_SequenceBlocks_AddSequenceBlock", "Home", FormMethod.Post, new { id = "submitForm" }))
{
if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
{
#Html.Hidden("HidInstitutionalProgram", ViewData["SelectedInstitutionProgram"].ToString())
<input type="submit" value="Add Sequence Block" class="btn btn-sm" />
}
}
</th>
</tr>
#foreach (var item in Model)
{
<tr>
#Html.HiddenFor(modelItem => item.SequenceBlockID)
#Html.HiddenFor(modelItem => item.InstitutionProgramID)
#Html.HiddenFor(modelItem => item.Minimum)
#Html.HiddenFor(modelItem => item.Maximum)
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.SequenceBlockDescription)
</td>
<td>
#Html.DisplayFor(modelItem => item.SequenceBlockRequired)
</td>
<td>
#Html.DisplayFor(modelItem => item.SequenceBlockTimingMethod)
</td>
<td>
#Html.DisplayFor(modelItem => item.Duration)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.ClerkshipModel)
</td>
<td>
#Html.ActionLink("Edit", "CI_SequenceBlocks_Edit_Form_Handler", new { id = item.SequenceBlockID, value = "Edit_SequenceBlock_ID", inInstitutionProgramID = item.InstitutionProgramID }) |
#Html.ActionLink("Maintain", "CI_SequenceBlocks_Edit_Form_Handler", new { id = item.SequenceBlockID, value = "Maintain_SequenceBlock_ID", inInstitutionProgramID = item.InstitutionProgramID })
</td>
</tr>
}
</table>
#if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
{
<div class="text-center" >
<ul class="pagination">
#for (var i = 1; i <= ViewBag.SearchMetaData.SearchNumberOfPages; i++)
{
if (ViewBag.SearchMetaData.SearchCurrentPage == #i)
{
<li class="active"> #Html.ActionLink(#i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", new { id = #i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)</li>
}
else
{
<li> #Html.ActionLink(#i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", "Home", new { id = #i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)</li>
}
}
</ul>
</div>
}
#using (Html.BeginForm("CI_SequenceBlocks_AddSequenceBlock", "Home", FormMethod.Post, new { id = "submitForm" }))
{
if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
{
<table class="table">
<tr>
<td>
#Html.Hidden("HidInstitutionProgram", ViewData["SelectedInstitutionProgram"].ToString())
</td>
</tr>
<tr>
<td>Add Sequence Block:</td>
<td> <input type="submit" value="Add Sequence Block" class="btn btn-sm" /> </td>
</tr>
</table>
}
}
____________NEW UPDATE____________
Found the issue:
I changed RedirectToActionPermanent to RedirectToAction. No more problems!
Thanks,
James

How to pass these 2 parameters to controller action method?

I have 2 actions methods, one them works as "Get" method but shows a list and just gets 1 value from user. The other updates the database with the value received. However, it seems like I'm not passing this value to the 2nd controller as I see it to be null when debugging code.
Can anyone help find my mistake ?
The action methods :
[AllowAnonymous]
public ActionResult AvaliaAluno()
{
var user = User.Identity.GetUserId();
if (User.IsInRole("Docentes") || User.IsInRole("Comissao"))
{
Docente d = db.Docentes.SingleOrDefault(x => x.UserId == user);
var vm = new ViewModels
{
Propostas = db.Propostas.Where(x => x.DocenteId == d.DocenteId).ToList(),
Alunos = db.Alunos.ToList(),
Candidaturas = db.Candidaturas.ToList()
};
return View(vm);
}
if (User.IsInRole("Empresas"))
{
Empresa d = db.Empresas.SingleOrDefault(x => x.UserId == user);
var vm = new ViewModels
{
Propostas = db.Propostas.Where(x => x.EmpresaId == d.EmpresaId).ToList(),
Alunos = db.Alunos.ToList(),
Candidaturas = db.Candidaturas.ToList()
};
return View(vm);
}
return View();
}
[AllowAnonymous]
public ActionResult ConfirmaAvaliacao(int id, decimal? avaliacao)
{
Candidatura c = db.Candidaturas.SingleOrDefault(x => x.CandidaturaId == id);
Proposta p = db.Propostas.SingleOrDefault(x => x.PropostaId == c.PropostaId);
if (User.IsInRole("Docentes") || User.IsInRole("Comissao"))
{
p.AvaliacaoDocenteAluno = avaliacao;
return RedirectToAction("AvaliaAluno");
}
if (User.IsInRole("Empresas"))
{
p.AvaliacaoEmpresaALuno = avaliacao;
return RedirectToAction("AvaliaAluno");
}
return RedirectToAction("Index", "Home");
}
and the view:
#model DEIS_ISEC.Models.ViewModels
<h3>Alunos Orientados por si</h3>
<table class="table">
<tr>
<th>
Nome do Aluno
</th>
<th>
Número do Aluno
</th>
<th>
Ramo Inscrito
</th>
<th>
Titulo da Proposta
</th>
<th>
Ramo da Proposta
</th>
<th>
Data de Início
</th>
<th>
Data de Fim
</th>
<th>
Avaliar
</th>
<th></th>
</tr>
#foreach (var item in Model.Propostas)
{
<tr>
#foreach (var c in Model.Candidaturas)
{
if (c.PropostaId == item.PropostaId)
{
foreach (var a in Model.Alunos)
{
if (a.AlunoId == c.AlunoId)
{
<td>
#Html.DisplayFor(modelItem => a.Nome) #Html.DisplayFor(modelItem => a.Apelido)
</td>
<td>
#Html.DisplayFor(modelItem => a.NumeroAluno)
</td>
<td>
#Html.DisplayFor(modelItem => a.Ramo)
</td>
}
}
}
}
<td>
#Html.DisplayFor(modelItem => item.Titulo)
</td>
<td>
#Html.DisplayFor(modelItem => item.Ramo)
</td>
<td>
#Html.DisplayFor(modelItem => item.DataInicio)
</td>
<td>
#Html.DisplayFor(modelItem => item.DataFim)
</td>
<td>
#Html.EditorFor(modelItem => item.AvaliacaoDocenteAluno, new { htmlAttributes = new { #class = "form-control", #style = "width:50% !important; min-width:50px;" } })
#Html.ValidationMessageFor(modelItem => item.AvaliacaoDocenteAluno, "", new { #class = "text-danger" })
</td>
<td>
#Html.ActionLink("Guardar", "ConfirmaAvaliacao", new { id = item.CandidaturaId, avaliacao = item.AvaliacaoDocenteAluno }, new { #class = "btn btn-info btn-md" })
</td>
</tr>
}
I believe that the moment when i get the input from user here :
#Html.EditorFor(modelItem => item.AvaliacaoDocenteAluno, new { htmlAttributes = new { #class = "form-control", #style = "width:50% !important; min-width:50px;" } })
#Html.ValidationMessageFor(modelItem => item.AvaliacaoDocenteAluno, "", new { #class = "text-danger" })
something unexpected happens.
I suggest you take a look at ASP.NET MVC 4 Helpers, Forms and Validation > Exercise 3: Creating the Edit View on how to implement an Edit mechanism with ASP.Net MVC.
In general, I recommend you go over the complete example in the link, as it covers many of the subjects required for building an ASP.Net MVC application.
Hope it helps!

I want to add paging on a multiple view but i get error

I got multiple views but I am getting an error when I use the NuGet.
Here is my controller Code:
public ActionResult Index(string searchString, int? id, int? courseID, int? idcom, int? elencoimo, int? elecoimobi,int? elencoinsta)
{
var viewmodel = new mainview();
viewmodel.elencoomonimi = db.ElencoOmonimis
.Where(s => s.Nome.Contains(searchString) || searchString == null || searchString == "")
.Include(s => s.ElencoProvinces.Select(t => t.ElencoImmobiliPerDiritti_E_Quote))
.Include(s => s.ElencoProvinces.Select(t => t.ElencoComunis))
.Include(s => s.ElencoProvinces.Select(t => t.ElencoImmobiliPerDiritti_E_Quote.Select(r => r.ElencoIntestatis)))
//.Include(i => i.ElencoOmonimi)
//.Include(i => i.ElencoImmobiliPerDiritti_E_Quote.Select(t => t.ElencoIntestatis))
//.Include(i => i.ElencoComunis)
.OrderBy(i => i.Id);
if (id != null)
{
ViewBag.elencoomonimiID = id.Value;
viewmodel.elencoprovince = viewmodel.elencoomonimi.Where(
i => i.Id == id.Value).Single().ElencoProvinces;
}
if (idcom != null)
{
ViewBag.ElencoImmobiliperID = idcom.Value;
viewmodel.elencointestati = viewmodel.elencoimmobiliperditti.Where(
x => x.Id == idcom.Value).Single().ElencoIntestatis;
}
if (elencoimo != null)
{
ViewBag.elecomuniID = elencoimo.Value;
viewmodel.elencocomuni = viewmodel.elencoprovince.Where(
r => r.Id == elencoimo.Value).Single().ElencoComunis;
}
if(elecoimobi != null)
{
ViewBag.ElencoimobID = elecoimobi.Value;
viewmodel.elencoimmobiliperditti = viewmodel.elencoprovince.Where(
q => q.Id == elecoimobi.Value).Single().ElencoImmobiliPerDiritti_E_Quote;
}
if (elencoinsta != null)
{
ViewBag.ElencoInstatiID = elencoinsta.Value;
viewmodel.elencointestati= viewmodel.elencoimmobiliperditti.Where(
e => e.Id == elencoinsta.Value).Single().ElencoIntestatis;
}
//if(elencoimo != null)
// ViewBag.elencoimoobiliID = id.Value
//viewmodel.elencoimmobiliperditti = db.ElencoImmobiliPerDiritti_E_Quote
// .Include(r => r.ElencoIntestatis)
// .OrderBy(r => r.Classe);
return View(viewmodel);
}
and here is my view:
#model automasis.Models.mainview
#{
ViewBag.Title = "Index";
}
Dashboard
#using (Html.BeginForm())
{
#Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" />
}
<table class="table">
<tr>
<th>
Nome
</th>
<th>
Cognome
</th>
<th>
Nome Cercato
</th>
<th>
Cognome Cercato
</th>
<th>
Data Di Nascita
</th>
<th>
Data Di Sesso
</th>
<th></th>
</tr>
#foreach (var item in Model.elencoomonimi)
{
string selectedRow = "";
if (item.Id == ViewBag.elencoomonimiID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.DisplayFor(modelItem => item.Nome)
</td>
<td>
#Html.DisplayFor(modelItem => item.Cognome)
</td>
<td>
#Html.DisplayFor(modelItem => item.NomeCercato)
</td>
<td>
#Html.DisplayFor(modelItem => item.CognomeCercato)
</td>
<td>
#Html.DisplayFor(modelItem => item.DataDiNascita)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sesso)
</td>
#*#if (item.ElencoProvinces != null)
{
#item.ElencoProvinces
}*#
<td>
#Html.ActionLink("Select", "Index", new { id = item.Id }) |
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
#if (Model.elencoprovince != null)
{
<h3>Provinca</h3>
<table class="table">
<tr>
<th></th>
<th>Provincia</th>
<th>Terreni</th>
<th>Fabricati</th>
</tr>
#foreach (var item in Model.elencoprovince)
{
string selectedRow = "";
if (item.Id == ViewBag.elencoprovinceID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Immobiliper", "Index", new { elecoimobi = item.Id })
</td>
<td>
#Html.ActionLink("Comune", "Index", new { elencoimo = item.Id })
</td>
<td>
#item.Provincia
</td>
<td>
#item.Terreni
</td>
<td>
#item.Fabbricati
</td>
<td class="hidden">
#if (item.ElencoImmobiliPerDiritti_E_Quote != null)
{
#item.ElencoImmobiliPerDiritti_E_Quote
}
</td>
</tr>
}
</table>
}
#if (Model.elencocomuni != null)
{
<h3>Elenco Comuni</h3>
<table class="table">
<tr>
<th></th>
<th>Particella</th>
<th>Sub</th>
<th>Titolarita</th>
<th>Ubicazione</th>
<th>Partita</th>
</tr>
#foreach (var item in Model.elencocomuni)
{
string selectedRow = "";
if (item.Id == ViewBag.elecomuniID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Select", "Index", new { id = item.Id })
</td>
<td>
#item.Comune
</td>
<td>
#item.Fabbricati
</td>
<td>
#item.Terreni
</td>
</tr>
}
</table>
}
#if (Model.elencointestati != null)
{
<h3>elencoimmobiliperditti</h3>
<table class="table">
<tr>
<th></th>
<th>Particella</th>
<th>Sub</th>
<th>Titolarita</th>
<th>Ubicazione</th>
<th>Partita</th>
</tr>
#foreach (var item in Model.elencointestati)
{
string selectedRow = "";
if (item.Id == ViewBag.ElencoInstatiID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Select", "Index", new { id = item.Id })
</td>
<td>
#item.Nominativo
</td>
<td>
#item.Titolarita
</td>
</tr>
}
</table>
}
#if (Model.elencoimmobiliperditti != null)
{
<h3>elencoimmobiliperditti</h3>
<table class="table">
<tr>
<th></th>
<th>Particella</th>
<th>Sub</th>
<th>Titolarita</th>
<th>Ubicazione</th>
<th>Partita</th>
</tr>
#foreach (var item in Model.elencoimmobiliperditti)
{
string selectedRow = "";
if (item.Id == ViewBag.ElencoInstatiID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Select", "Index", new { elencoinsta = item.Id })
</td>
<td>
#item.Classe
</td>
<td>
#item.Consistenza
</td>
<td>
#item.Foglio
</td>
<td class="hidden">
#if (item.Partita != null)
{
#item.Rendita
}
</td>
</tr>
}
</table>
}

Default routing don't work with pagination on mvc 5

Greetings I have developed an ASP.NET MVC 5 application. I'm using pagination, it works but when I want to call a query that I wrote I get the error:
Additional information: Object reference not set to an instance of an object.
I think its a problem on routing but I can't figure it out.
Here is my controller:
public ActionResult Index(string searchString, int? omonimipage, int? id, int? courseID, int? idcom, int? elencoimo, int? elecoimobi, int? elencoinsta, int? page)
{
int elencoomoninumber = (omonimipage ?? 1);
var viewmodel = new mainview();
viewmodel.elencoomonimi = db.ElencoOmonimis
.Include(s => s.ElencoProvinces)
.Include(s => s.ElencoProvinces.Select(r => r.ElencoImmobiliPerDiritti_E_Quote))
.Include(s => s.ElencoProvinces.Select(r => r.ElencoComunis))
.Include(s => s.ElencoProvinces.Select(r => r.ElencoImmobiliPerDiritti_E_Quote.Select(q => q.ElencoIntestatis)))
.OrderBy(i => i.Id).ToPagedList(elencoomoninumber,6);
if (id != null)
{
ViewBag.elencoprovinceID = id.Value;
viewmodel.elencoprovince = viewmodel.elencoomonimi.Where(
i => i.Id == id.Value).SingleOrDefault().ElencoProvinces;
}
if (idcom != null)
{
ViewBag.ElencoImmobiliperID = idcom.Value;
viewmodel.elencointestati = viewmodel.elencoimobili.Where(
r => r.Id == idcom.Value).Single().ElencoIntestatis;
}
if (elencoimo != null)
{
ViewBag.elecomuniID = elencoimo.Value;
viewmodel.elencocomuni = viewmodel.elencoprovince.Where(
r => r.Id == elencoimo.Value).Single().ElencoComunis;
}
if (elecoimobi != null)
{
ViewBag.ElencoimobID = elecoimobi.Value;
viewmodel.elencoimobili = viewmodel.elencoprovince.Where(
q => q.Id == elecoimobi.Value).Single().ElencoImmobiliPerDiritti_E_Quote;
}
if (elencoinsta != null)
{
ViewBag.ElencoInstatiID = elencoinsta.Value;
viewmodel.elencointestati = viewmodel.elencointestati = db.ElencoImmobiliPerDiritti_E_Quote.Where(
e => e.Id == elencoinsta.Value).Single(i =>i.Id == elencoinsta.Value).ElencoIntestatis;
}
return View(viewmodel);
}
and here is my view:
#model automa0._1.Models.mainview
#using PagedList.Mvc;
#{
ViewBag.Title = "Index";
}
Dashboard
#using (Html.BeginForm())
{
#Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" />
}
<div id="content">
<table class="table">
<tr>
<th>
Nome
</th>
<th>
Cognome
</th>
<th>
Data Di Nascita
</th>
<th>
Codice Fiscale
</th>
<th></th>
</tr>
#foreach (var item in Model.elencoomonimi)
{
string selectedRow = "";
if (item.Id == ViewBag.elencoomonimiID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.DisplayFor(modelItem => item.CognomeCercato)
</td>
<td>
#Html.DisplayFor(modelItem => item.NomeCercato)
</td>
<td>
#Html.DisplayFor(modelItem => item.Cognome)
</td>
<td>
#Html.DisplayFor(modelItem => item.DataDiNascita)
</td>
<td>
#Html.DisplayFor(modelItem => item.CodiceFiscale)
</td>
<td>
#Html.ActionLink("Provinca", "Index", new { id = item.Id }) |
</td>
</tr>
}
</div>
</>
<div id="contentPager">
Page #(Model.elencoomonimi.PageCount < Model.elencoomonimi.PageNumber ? 0 : Model.elencoomonimi.PageNumber) of #Model.elencoomonimi.PageCount
#Html.PagedListPager(Model.elencoomonimi, page => Url.Action("Index", new { omonimipage = page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
</div>
</table>
#if (Model.elencoprovince != null)
{
<h3>Provinca</h3>
<table class="table">
<tr>
<th></th>
<th>Provincia</th>
<th>Terreni</th>
<th>Fabbricati</th>
</tr>
#foreach (var item in Model.elencoprovince)
{
string selectedRow = "";
if (item.Id == ViewBag.elencoprovinceID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Select", "Index", new { elecoimobi = item.Id })
</td>
<td>
#item.Provincia
</td>
<td>
#item.Terreni
</td>
<td>
#item.Fabbricati
</td>
#if (item.ElencoImmobiliPerDiritti_E_Quote != null)
{
#item.ElencoImmobiliPerDiritti_E_Quote
}
</tr>
}
</table>
}
#if (Model.elencoimobili != null)
{
<h3>elencoimmobiliperditti</h3>
<table class="table">
<tr>
<th></th>
<th>Classe</th>
<th>Consistenza</th>
<th>Foglio</th>
</tr>
#foreach (var item in Model.elencoimobili)
{
string selectedRow = "";
if (item.Id == ViewBag.ElencoImmobiliperID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Select", "Index", new { elencoinsta = item.Id })
</td>
<td>
#item.Classe
</td>
<td>
#item.Consistenza
</td>
<td>
#item.Foglio
</td>
</tr>
}
</table>
}
#if (Model.elencointestati != null)
{
<h3>elneco Intestati</h3>
<table class="table">
<tr>
<th>CodiceFiscale</th>
<th>Nominativo</th>
<th>Titolarita</th>
</tr>
#foreach (var item in Model.elencointestati)
{
string selectedRow = "";
if (item.Id == ViewBag.ElencoImmobiliperID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Select", "Index", new { id = item.Id })
</td>
<td>
#item.CodiceFiscale
</td>
<td>
#item.Nominativo
</td>
<td>
#item.Titolarita
</td>
</tr>
}
</table>
}
on default its working but wen i navigate to page 2 the url its: http://localhost:49208/ElencoOmonimis?omonimipage=2
Thank you.

Show Limited Number of Page Links at a time in ASP.net MVC

I am displaying page links with the help of PagedList in ASP.net MVC. But the issue is if there are 100 pages then all links show at the same time but i want to show 10 links at a time. How can it be achieved. Please Help. Thanks.. Below is the working Code.
Index.cshtml
#model PagedList.IPagedList<MvcPagingList.Models.Employee>
#{
ViewBag.Title = "Employees";
}
<link href="#Url.Content("~/bootstrap/css/bootstrap.min.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/bootstrap/css/bootstrap.css")" rel="stylesheet" type="text/css" />
<h2>
Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm())
{
<p>
Search By Name : #Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" /></p>
}
<table>
<tr>
<th>
#Html.Label("Last Name")
</th>
<th>
#Html.Label("First Name")
</th>
<th>
#Html.Label("Department ID")
</th>
<th>
#Html.ActionLink("Salery", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.DepartmentID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Salary)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.EmployeeID }) |
#Html.ActionLink("Details", "Details", new { id = item.EmployeeID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.EmployeeID })
</td>
</tr>
}
</table>
<div class="pagination pagination-right">
<ul>
<li>
#for (int p = 1; p <= Model.PageCount; p++)
{
#p
}
</li>
</ul>
</div>
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcPagingList.Models;
using PagedList;
namespace MvcPagingList.Controllers
{
public class HomeController : Controller
{
EmployeeEntities dbEntities = new EmployeeEntities();
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Salery desc" : "";
//ViewBag.DateSortParm = sortOrder == "HireDate" ? "HireDate desc" : "HireDate";
if (Request.HttpMethod == "GET")
{
searchString = currentFilter;
}
else
{
page = 1;
}
ViewBag.CurrentFilter = searchString;
var employees = from s in dbEntities.Employees
select s;
if (!String.IsNullOrEmpty(searchString))
{
employees = employees.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper())
|| s.FirstName.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "Salery desc":
employees = employees.OrderByDescending(s => s.LastName);
break;
default:
employees = employees.OrderBy(s => s.LastName);
break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(employees.ToPagedList(pageNumber, pageSize));
}
}
}
I faced the same issue & solved it by studying the following Code :-
http://msdn.microsoft.com/en-us/magazine/gg650669.aspx
You will have to use webgrid for this.
http://www.w3schools.com/aspnet/showfile_c.asp?filename=try_webpages_cs_004

Categories