C# HTML.Actionlink strange behaviour on server - c#

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

Related

Why am I am getting null entry for parameter 'CarLotID' of non-nullable type 'System.Int32' for method 'ActionResult DisplaySearchResults()

I am creating an MVC application and I am trying to display data on my table based on the selected values for multiple dropdowns once a button is clicked. I think I am assigning all the values in my code but I am new to coding so I am not sure if I am missing something.
This is my view
#model IgnitionHub2._0.Models.Car
#{
ViewBag.Title = "Car Search Page";
}
<h2>Cars</h2>
<div class="center-div">
<div class="form-inline">
#Html.DropDownListFor(model => model.CarLotID, new SelectList(Model.CarLotList, "CarLotID", "LotName"), "Select Car Lot", new { #class = "form-control" })
#Html.DropDownListFor(model => model.Model.MakeID, new SelectList(Model.MakeList, "MakeID", "Name"), "Select Make", new { #class = "form-control" })
#Html.DropDownListFor(model => model.ModelID, new SelectList(Model.ModelList, "ModelID", "Name"), "Select Model", new { #class = "form-control" })
<button id="search">Search</button>
</div>
</div>
<div id="searchResults">
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
$(document).ready(
function () {
var makeUrl = '#Url.Action("GetCarDetails")';
var models = $('#ModelID')
$('#Model_MakeID').change(function () {
models.empty();
$.getJSON(makeUrl, { MakeID: $(this).val() },function(data){
if (!data) {
return;
}
models.append($('<option></option>').val('').text('Please select'));
$.each(data, function(index, item) {
models.append($('<option></option>').val(item.Value).text(item.Name));
});
});
})
})
$(document).ready(function () {
var url = '#Url.Action("DisplaySearchResults","Car")';
$('#search').click(function () {
var carLotID = $('#CarLotID').val();
var makeID = $('#Model_MakeID').val();
var modelID = $('#ModelID').val();
alert(modelID);
$('#searchResults').load(url, { CarLotID: carLotID, MakeID: makeID, ModelID: modelID });
})
})
This is my Partial view
#model IEnumerable<IgnitionHub2._0.Models.Car>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Year)
</th>
<th>
#Html.DisplayNameFor(model => model.Color)
</th>
<th>
#Html.DisplayNameFor(model => model.Mileage)
</th>
<th>
#Html.DisplayNameFor(model => model.BodyType)
</th>
<th>
#Html.DisplayNameFor(model => model.Drive)
</th>
<th>
#Html.DisplayNameFor(model => model.Available)
</th>
<th>
#Html.DisplayNameFor(model => model.Model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.CarLot.LotName)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Year)
</td>
<td>
#Html.DisplayFor(modelItem => item.Color)
</td>
<td>
#Html.DisplayFor(modelItem => item.Mileage)
</td>
<td>
#Html.DisplayFor(modelItem => item.BodyType)
</td>
<td>
#Html.DisplayFor(modelItem => item.Drive)
</td>
<td>
#Html.DisplayFor(modelItem => item.Available)
</td>
<td>
#Html.DisplayFor(modelItem => item.Model.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.CarLot.LotName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.CarID }) |
#Html.ActionLink("Details", "Details", new { id=item.CarID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.CarID })
</td>
</tr>
}
</table>
And this is my controller
public ActionResult Index()
{
var cars = db.Cars.Include(c => c.Model).Include(c => c.CarLot);
var makeList = db.Makes.ToList();
var modelList = db.Models.ToList();
var carLotList = db.CarLots.ToList();
var ViewModel = new Car
{
CarList = cars,
MakeList = makeList,
ModelList= modelList,
CarLotList = carLotList
};
return View(ViewModel);
}
public ActionResult DisplaySearchResults(int CarLotID, int MakeID, int ModelID)
{
var model = db.Cars.Where(c => c.Model.MakeID == MakeID && c.ModelID == ModelID &&
c.CarLotID == CarLotID).ToList();// build list based on parameter searchText
return PartialView("_Index", model);
}
public ActionResult _Index()
{
var cars = new List<Car>();
return PartialView(cars);
}
public JsonResult GetCarDetails(int MakeID)
{
db.Configuration.ProxyCreationEnabled = false;
var data = GetModels(MakeID).ToList();
//data = data.Where(x => x.Model.MakeID == MakeID).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
Please Help! Thank you in advance!
According to the documentation, https://api.jquery.com/load/, .load() uses POST http request if you're passing an object as parameter, which you are doing right now with;
// {CarLotID:carLotID,MakeID:makeID,ModelID:modelID} is an object
$('#searchResults').load(url, { CarLotID: carLotID, MakeID: makeID, ModelID: modelID });
OPTION 1-- Since you didn't write your action method to be POST, you could just configure your .load() to use GET.
Use the code below for .load();
$('#searchResults').load(url+"?CarLotID="+carLotID+"&MakeID="+makeID+"&ModelID="+modelID);
then change
#Html.DropDownListFor(model => model.ModelID, new SelectList(Model.ModelList, "ModelID", "Name"), "Select Model", new { #id="ModelID", #class = "form-control" })
In your loop to refill the dropdown, use this instead;
$.each(data, function(index, item) {
models.append($('<option value="+item.MakeID+"></option>').text(item.Name));
});
updated script:
$('#Model_MakeID').change(function(){
models.empty();
$.getJSON(makeUrl, { MakeID: $(this).val() }, function(data){
if (!data) {
return;
}
models.append($('<option></option>').val('').text('Please select'));
// update this
$.each(data, function(index, item) {
models.append($('<option value="+item.Value+"></option>').text(item.Name));
});
});
});
OR OPTION 2-- just add [HttpPOST] attribute to your controller action.
[HttpPost] // add this
public ActionResult DisplaySearchResults(int CarLotID, int MakeID, int ModelID)
{
...
}

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!

Does not contain a definition for 'ToPagedList'

I am trying to implement Pagination to my code using PagedList and PagedList.Mvc
The problem I am facing is that I am getting an error
'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in
System.Core.dll but was not handled in user code
Additional information: 'System.Collections.Generic.List'
does not contain a definition for 'ToPagedList'
Following is my code for PJController.cs:
public ActionResult Index(SearchPostedJob objSearchPostedJob, int? page)
{
Result res = null;
try
{
objSearchPostedJob.page = (objSearchPostedJob.page == null ? 1 : objSearchPostedJob.page);
ViewBag.SearchPostedJob = objSearchPostedJob;
res = objPostedJobDAL.GetPostedJobs(ApplicationSession.CurrentUser.RecruiterId);
if (res.Status)
{
page = 1;
ViewBag.Message = "";
}
else
{
ViewBag.Message = Common.GetMessage(res.MessageId, "[Master]", "Keyword");
}
}
catch (Exception ex)
{
Common.WriteLog(ex);
throw ex;
}
var result = res.Results;
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(result.ToPagedList(pageNumber, pageSize));
}
Below is the code for Index.cshtml:
#model PagedList.IPagedList<NOS.SC.PJ>
#using PagedList.Mvc;
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="postjob-form">
#using (Html.BeginForm("Index", "PostedJob", FormMethod.Get))
{
<div class="j_search" style="margin-left:3%;">
<input class="form-control" name="SearchKeyword" id="SearchKeyword" placeholder="Search Keyword" />
</div>
<div class="j_search">
<input id="pinput1" name="JobLocation" class="form-control" type="text" value="#ViewBag.SearchPostedJob.JobLocation" placeholder="Enter a location">
<input id="Latitude" name="Latitude" type="hidden" value="#ViewBag.SearchPostedJob.Latitude">
<input id="Longitude" name="Longitude" type="hidden" value="#ViewBag.SearchPostedJob.Longitude">
</div>
<div class="j_search">
<select class="form-control" name="Experience" id="Experience">
<option value="" selected>Select Experience</option>
#for (int i = 1; i <= 10; i++)
{
<option value="#i" #(ViewBag.SearchPostedJob.Experience == i ? "selected" : "")>#i</option>
}
</select>
</div>
<div class="j_search">
<select class="form-control" name="Salary" id="Salary">
<option value="" selected>Select Salary</option>
#for (int i = 1; i <= 10; i++)
{
<option value="#i" #(ViewBag.SearchPostedJob.Salary == i ? "selected" : "")>#i</option>
}
</select>
</div>
<div class="add-btn"><a class="btn btn-primary" href="~/PostedJob/Save?returnUrl=/PostedJob/Index">Add New Opening</a></div>
}
</div>
<div>
<table class="table" id="myTable">
<tr>
<th>
#Html.DisplayNameFor(model => model[0].JobTitle)
</th>
<th>
#Html.DisplayNameFor(model => model[0].JobLocation)
</th>
<th>
#Html.DisplayNameFor(model => model[0].NumberOfPositions)
</th>
<th>
#Html.DisplayNameFor(model => model[0].ValidFrom)
</th>
<th>
#Html.DisplayNameFor(model => model[0].ValidTo)<br />
</th>
<th>
#Html.DisplayNameFor(model => model[0].JobReference)
</th>
<th>
#Html.DisplayNameFor(model => model[0].Status)
</th>
<th>
Application
</th>
<th>
CloneJob
</th>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.JobTitle)
</td>
<td>
#Html.DisplayFor(modelItem => item.JobLocation)
</td>
<td>
#Html.DisplayFor(modelItem => item.NumberOfPositions)
</td>
<td>
#Html.DisplayFor(modelItem => item.ValidFrom)
</td>
<td>
#Html.DisplayFor(modelItem => item.ValidTo)<br />
#* #Html.ActionLink("Delete Resume", "DeleteResume", new { ResumeId = Model.ResumeId, returnUrl = "/Nurse/ProfileView" }, new { #class = "btnViewJobDetails" })*#
#if (!item.IsExtendJob)
{
#Html.ActionLink("ExtendJob", "ExtendJob", new { PostedJobId = item.PostedJobId, IsExtendJob = item.IsExtendJob, returnUrl = "/PostedJob/Index" }, new { #class = "btnViewJobDetails" })
}
else
{
<span class="pull-right" style="font-weight:bold; color:red;">JobExtended</span>
}
</td>
<td>
#Html.DisplayFor(modelItem => item.JobReference)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</td>
<td>
#Html.ActionLink("Applied(" + item.AppliedCnt + ")", "JobView", new { PostedJobId = item.PostedJobId, returnUrl = "/PostedJob/Index" }, new { #class = "btnViewJobDetails" })
</td>
<td>
#Html.ActionLink("JobClone", "CloneJob", new { PostedJobId = item.PostedJobId, returnUrl = "/PostedJob/Index" }, new { #class = "btnViewJobDetails" })
</td>
</tr>
}
</table>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>
#section Scripts
{
#Scripts.Render("~/bundles/jqueryui")
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/jqueryval")
<script>
function initMap() {
var input = document.getElementById('pinput1');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function () {
var place = autocomplete.getPlace();
console.log(JSON.stringify(place));
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
var latlong = JSON.parse(JSON.stringify(place.geometry.location));
document.getElementById('Latitude').value = latlong.lat;
document.getElementById('Longitude').value = latlong.lng;
});
}
initMap();
</script>
<script>
$(document).ready(function () {
$("#SearchKeyword").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
<script>
$(document).ready(function () {
$("#pinput1").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
}
Try using this:
public ActionResult Index(FilterPostedJob objFilterPostedJob, int? page)
{
Result res = null;
try
{
objFilterPostedJob.CreatedBy = ApplicationSession.CurrentUser.RecruiterId;
objFilterPostedJob.page = (objFilterPostedJob.page == null ? 1 : objFilterPostedJob.page);
ViewBag.SearchPostedJob = objFilterPostedJob;
res = objPostedJobDAL.GetPostedJobs(objFilterPostedJob);
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(((List<PostedJob>)res.Results).ToPagedList(pageNumber, pageSize));
}
catch (Exception ex)
{
Common.WriteLog(ex);
throw ex;
}
}
Using ToPagedList is an added advantage as all you need to do is to pass the PageNumber and PageSize

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.

Categories