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!
Related
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)
{
...
}
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
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>
}
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.
I try to add my files into DropDownList, all my files with the relevant property already return by the controller:
// GET: /WebMail/
public ActionResult Index()
{
var fileNameList = db.Captures.ToList().Where(x => x.robotFamily == "WebMail");
//return View(db.Captures.ToList().Where(x => x.robotFamily == "WebMail"));
ViewBag.Files = fileNameList;
return View();
}
Index.cshtml
#model IEnumerable<AutomationCapturesMVC.Models.Capture>
#{
//ViewBag.Title = "Index";
}
<table class="table">
<tr>
<th style="font-size: 20px">
#Html.DisplayNameFor(model => model.fileName)
</th>
<th></th>
</tr>
#Html.DropDownList("Id", (IEnumerable<AutomationCapturesMVC.Models.Capture>)ViewBag.Files, new { id = "WebMail", #class = "btn dropdown-toggle" })
#foreach (var item in Model)
{
<tr>
<td style="font-size: 15px">
#Html.DisplayFor(modelItem => item.fileName)
</td>
<td>
#Html.ActionLink("File Details", "Details", new { id = item.id })
</td>
</tr>
}
</table>
this is my page error:
http://s21.postimg.org/983eokpfq/1231231313.jpg
How about the following?
In controller
public ActionResult Index()
{
var fileNames = GetDatabaseFileNames();
var fileNameList = fileNames.Select(d => new SelectListItem { Text = d.FileName, Value = d.FileName.ToString() }).ToList();
ViewBag.Files = fileNameList;
return View();
}
In View
#Html.DropDownList("DatabaseFiles", (IEnumerable<SelectListItem>)ViewBag.Files, new { id = "DatabaseFiles", #class = "btn dropdown-toggle" })