ASP.Net MVC Filtering - c#

THEAPP:
ASP.NET MVC CRUD APPLICATION
Visual Studio 2013
DONE:
Created the filter option by rendering the COLUMN (sector) values into a drop down list. Hence the user can select a sector on from the DROP DOWN LIST & CLICK SUBMIT to FILTER RECORDS in the table
REQUIREMENT:
Filtering Records on a table based on the COLUMN (Sector) values.
In the TABLE of records suppose COLUMN [Sector] has =>
IT, MANAGEMENT, MARKETING, abc, xyz,
It is required to get all the Sector values on more like a NAVIGATION BAR. Once a Sector (MARKETING) is clicked on this LIST the TABLE should list the Only the records with that SECTOR (MARKETING)
Note: User is able to insert new records so is able to create new sector name so links rendered to the navigation bar should be dynamic
As I am a newbie to the language and MVC I have no clue how I could instead of using the DROP DOWN LIST use a LIST VIEW
Controller Code
PipelineController.cshtml
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PipelineApp.Models;
namespace PipelineApp.Controllers
{
public class PipelineController : Controller
{
private PipelineEntities db = new PipelineEntities();
// GET: /Pipeline/
//public ActionResult Index()
//{
// return View(db.Pipelinedatas.ToList());
//}
//CUSTOM GET: /Pipelinedata/Sector filtering
//public ActionResult Index(string sector)
//{
// ViewBag.Sector = (from r in db.Pipelinedatas
// select r.Sector).Distinct();
// var model = from r in db.Pipelinedatas
// where r.Sector == sector || sector == null || sector == ""
// select r;
// return View(model);
//}
//CUSTOM GET: /Pipelinedata/ Sector Filtering/ Sort Order
public ActionResult Index(string sector, string sortOrder, int? page)
{
//Filter Secors ------------------------------
ViewBag.Sector = (from r in db.Pipelinedatas
select r.Sector).Distinct();
//---------------------------------------------
var model = from r in db.Pipelinedatas
where r.Sector == sector || sector == null || sector == ""
select r;
//Sort Order ----------------------------------
ViewBag.CurrentSort = sortOrder; //Paging
ViewBag.EmployerSortParm = String.IsNullOrEmpty(sortOrder) ? "emp_name" : "";
ViewBag.ITOSortParm = String.IsNullOrEmpty(sortOrder) ? "ITO" : "";
ViewBag.JanSortParm = String.IsNullOrEmpty(sortOrder) ? "January" : "";
ViewBag.FebSortParm = String.IsNullOrEmpty(sortOrder) ? "February" : "";
ViewBag.MarSortParm = String.IsNullOrEmpty(sortOrder) ? "March" : "";
ViewBag.AprSortParm = String.IsNullOrEmpty(sortOrder) ? "April" : "";
ViewBag.MaySortParm = String.IsNullOrEmpty(sortOrder) ? "May" : "";
ViewBag.JunSortParm = String.IsNullOrEmpty(sortOrder) ? "June" : "";
ViewBag.JulSortParm = String.IsNullOrEmpty(sortOrder) ? "July" : "";
ViewBag.AugSortParm = String.IsNullOrEmpty(sortOrder) ? "August" : "";
ViewBag.SepSortParm = String.IsNullOrEmpty(sortOrder) ? "September" : "";
ViewBag.OctSortParm = String.IsNullOrEmpty(sortOrder) ? "October" : "";
ViewBag.NovSortParm = String.IsNullOrEmpty(sortOrder) ? "November" : "";
ViewBag.DecSortParm = String.IsNullOrEmpty(sortOrder) ? "December" : "";
ViewBag.SectorSortParm = sortOrder == "sec" ? "ITO" : "sec";
switch (sortOrder)
{
case "emp_name":
model = model.OrderByDescending(s => s.Employer);
break;
case "sec":
model = model.OrderBy(s => s.Sector);
break;
case "ITO":
model = model.OrderByDescending(s => s.ITONumber);
break;
case "January":
model = model.OrderByDescending(s => s.Jan);
break;
case "February":
model = model.OrderByDescending(s => s.Feb);
break;
case "March":
model = model.OrderByDescending(s => s.Mar);
break;
case "April":
model = model.OrderByDescending(s => s.Apr);
break;
case "May":
model = model.OrderByDescending(s => s.May);
break;
case "June":
model = model.OrderByDescending(s => s.Jun);
break;
case "July":
model = model.OrderByDescending(s => s.Jul);
break;
case "August":
model = model.OrderByDescending(s => s.Aug);
break;
case "September":
model = model.OrderByDescending(s => s.Sep);
break;
case "October":
model = model.OrderByDescending(s => s.Oct);
break;
case "November":
model = model.OrderByDescending(s => s.Nov);
break;
case "December":
model = model.OrderByDescending(s => s.Dec);
break;
default:
model = model.OrderBy(s => s.Id);
break;
}
//---------------------------------------------
//Paging --------------------------------------
//int pageSize = 3;
//int pageNumber = (page ?? 1);
//return View(model.ToPagedList(pageNumber, pageSize));
//---------------------------------------------
return View(model);
}
// GET: /Pipeline/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
if (pipelinedata == null)
{
return HttpNotFound();
}
return View(pipelinedata);
}
// GET: /Pipeline/Create
public ActionResult Create()
{
return View();
}
// POST: /Pipeline/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Id,Employer,ITONumber,Description,TECNumber,TECVersion,Level,Credits,Duration,Sector,Status,Approval,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec")] Pipelinedata pipelinedata)
{
if (ModelState.IsValid)
{
db.Pipelinedatas.Add(pipelinedata);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pipelinedata);
}
// GET: /Pipeline/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
if (pipelinedata == null)
{
return HttpNotFound();
}
return View(pipelinedata);
}
// POST: /Pipeline/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="Id,Employer,ITONumber,Description,TECNumber,TECVersion,Level,Credits,Duration,Sector,Status,Approval,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec")] Pipelinedata pipelinedata)
{
if (ModelState.IsValid)
{
db.Entry(pipelinedata).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pipelinedata);
}
// GET: /Pipeline/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
if (pipelinedata == null)
{
return HttpNotFound();
}
return View(pipelinedata);
}
// POST: /Pipeline/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
db.Pipelinedatas.Remove(pipelinedata);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
View Code
Index.cshtml
#model IEnumerable<PipelineApp.Models.Pipelinedata>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
<text> Sectors </text>
#Html.DropDownList("sector", new SelectList(ViewBag.Sector))
<input class="btn" type="submit" value="Filter" />
}
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.ActionLink("Employer", "Index", new { sortOrder = ViewBag.EmployerSortParm })
#*#Html.DisplayNameFor(model => model.Employer)*#
</th>
<th>
#Html.ActionLink("ITONumber", "Index", new { sortOrder = ViewBag.ITOSortParm })
#*#Html.DisplayNameFor(model => model.ITONumber)*#
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.TECNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.TECVersion)
</th>
<th>
#Html.DisplayNameFor(model => model.Level)
</th>
<th>
#Html.DisplayNameFor(model => model.Credits)
</th>
<th>
#Html.DisplayNameFor(model => model.Duration)
</th>
<th>
#Html.ActionLink("Sector", "Index", new { sortOrder = ViewBag.SectorSortParm })
#*#Html.DisplayNameFor(model => model.Sector)*#
</th>
<th>
#Html.DisplayNameFor(model => model.Status)
</th>
<th>
#Html.DisplayNameFor(model => model.Approval)
</th>
<th>
#Html.ActionLink("Jan", "Index", new { sortOrder = ViewBag.JanSortParm })
#*#Html.DisplayNameFor(model => model.Jan)*#
</th>
<th>
#Html.ActionLink("Feb", "Index", new { sortOrder = ViewBag.FebSortParm })
#*#Html.DisplayNameFor(model => model.Feb)*#
</th>
<th>
#Html.ActionLink("Mar", "Index", new { sortOrder = ViewBag.MarSortParm })
#*#Html.DisplayNameFor(model => model.Mar)*#
</th>
<th>
#Html.ActionLink("Apr", "Index", new { sortOrder = ViewBag.AprSortParm })
#*#Html.DisplayNameFor(model => model.Apr)*#
</th>
<th>
#Html.ActionLink("May", "Index", new { sortOrder = ViewBag.MaySortParm })
#*#Html.DisplayNameFor(model => model.May)*#
</th>
<th>
#Html.ActionLink("Jun", "Index", new { sortOrder = ViewBag.JunSortParm })
#*#Html.DisplayNameFor(model => model.Jun)*#
</th>
<th>
#Html.ActionLink("Jul", "Index", new { sortOrder = ViewBag.JulSortParm })
#*#Html.DisplayNameFor(model => model.Jul)*#
</th>
<th>
#Html.ActionLink("Aug", "Index", new { sortOrder = ViewBag.AugSortParm })
#*#Html.DisplayNameFor(model => model.Aug)*#
</th>
<th>
#Html.ActionLink("Sep", "Index", new { sortOrder = ViewBag.SepSortParm })
#*#Html.DisplayNameFor(model => model.Sep)*#
</th>
<th>
#Html.ActionLink("Oct", "Index", new { sortOrder = ViewBag.OctSortParm })
#*#Html.DisplayNameFor(model => model.Oct)*#
</th>
<th>
#Html.ActionLink("Nov", "Index", new { sortOrder = ViewBag.NovSortParm })
#*#Html.DisplayNameFor(model => model.Nov)*#
</th>
<th>
#Html.ActionLink("Dec", "Index", new { sortOrder = ViewBag.DecSortParm })
#*#Html.DisplayNameFor(model => model.Dec)*#
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Employer)
</td>
<td>
#Html.DisplayFor(modelItem => item.ITONumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.TECNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.TECVersion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Level)
</td>
<td>
#Html.DisplayFor(modelItem => item.Credits)
</td>
<td>
#Html.DisplayFor(modelItem => item.Duration)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sector)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</td>
<td>
#Html.DisplayFor(modelItem => item.Approval)
</td>
<td>
#Html.DisplayFor(modelItem => item.Jan)
</td>
<td>
#Html.DisplayFor(modelItem => item.Feb)
</td>
<td>
#Html.DisplayFor(modelItem => item.Mar)
</td>
<td>
#Html.DisplayFor(modelItem => item.Apr)
</td>
<td>
#Html.DisplayFor(modelItem => item.May)
</td>
<td>
#Html.DisplayFor(modelItem => item.Jun)
</td>
<td>
#Html.DisplayFor(modelItem => item.Jul)
</td>
<td>
#Html.DisplayFor(modelItem => item.Aug)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sep)
</td>
<td>
#Html.DisplayFor(modelItem => item.Oct)
</td>
<td>
#Html.DisplayFor(modelItem => item.Nov)
</td>
<td>
#Html.DisplayFor(modelItem => item.Dec)
</td>
<td>
#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>
references:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/filter-records-in-mvc/
http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

Simply use ajax to invoke the action method "Index", in your case, on click of a tab in the navigation bar. Your ajax code would look something like this.
$.ajax({
type: "GET",
url: "/SomeController/Index",
data: { 'sector': selectedSector },
success: function (data) {
// Here you can assign the partial view returned to an encompassing div
$('#sectorDiv').html(data);
},
error: function (xhr, status, message) {
}
});

#using (Ajax.BeginForm("Index",new AjaxOptions { UpdateTargetId = "result" }))
{
#Html.DropDownList("sector", new SelectList(ViewBag.Sector), new { #class = "chzn-select select-block-level" })
<input class="btn" type="submit" value="Filter" />
}
<div id="result">
#Html.Partial("gridPartial")
</div>

Related

ASP NET Core MVC database list view with sort all columns

I have a list view in my FileManager.cshtml page (code below) and I need to implement sort function to all columns that are displayed on this view. I looked through some examples on the web and YouTube but there are Javascript functions or "hand-made" namespaces. Is it possible to do it without JScript?
Thank you for help!
Function in my controller that displays list view from dbo.Files filtered by logged user ID:
private readonly TextCloudContext Context;
public IActionResult FileManager()
{
var user = _userManager.GetUserId(User);
var items = Context.Files.Where(f => f.UserID == user).ToList();
return View(items);
}
String in TextCloudContext.cs with get and set values in "Files" table from my SQL Server table "Files":
public DbSet<File> Files { get; set; }
File.cs model that initialize values for Db parameter in TextCloudContext and display column names in my FileManagerView.cshtml
public class File
{
public int Id { get; set; }
[Display(Name = "File Name")]
public string Name { get; set; }
public string Data { get; set; }
[Display(Name = "File Type")]
public string Extension { get; set; }
[Display(Name = "Date")]
public string Date { get; set; }
public string UserID { get; set; }
public TextCloudUser User { get; set; }
}
and finally View with table class:
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Extension)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<th>
#Html.DisplayName("Actions")
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Extension)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td> - this razor Html doesn't work yet
#Html.ActionLink("Download", "Download", new { fileName = item.ToString() }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
Based on this docs,here is a working demo like below:
View:
#model IEnumerable<File>
<table class="table">
<thead>
<tr>
<th>
<a asp-action="FileManager" asp-route-sortOrder="#ViewData["NameSortParm"]">#Html.DisplayNameFor(model => model.Name)</a>
</th>
<th>
<a asp-action="FileManager" asp-route-sortOrder="#ViewData["ExtensionSortParm"]">#Html.DisplayNameFor(model => model.Extension)</a>
</th>
<th>
<a asp-action="FileManager" asp-route-sortOrder="#ViewData["DateSortParm"]">#Html.DisplayNameFor(model => model.Date)</a>
</th>
<th>
#Html.DisplayName("Actions")
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Extension)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.ActionLink("Download", "Download", new { fileName = item.ToString() }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>
Controller:
public IActionResult FileManager(string sortOrder)
{
//var user = _userManager.GetUserId(User);
//var items = Context.Files.Where(f => f.UserID == user); //you may change this..
//for easy testing,i just create data manually..
var items = new List<File>()
{
new File(){ Id=1, Data="a", Date="2019-8-9", Extension=".jpg", Name="file1", UserID="1"},
new File(){ Id=1, Data="b", Date="2019-7-9", Extension=".png", Name="file2", UserID="2"},
new File(){ Id=1, Data="c", Date="2019-5-8", Extension=".png", Name="file3", UserID="3"},
new File(){ Id=1, Data="d", Date="2019-4-7", Extension=".jpg", Name="file4", UserID="4"}
}.AsQueryable();
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
ViewData["ExtensionSortParm"] = sortOrder == "Extension" ? "ext_desc" : "Extension";
switch (sortOrder)
{
case "name_desc":
items = items.OrderByDescending(s => s.Name);
break;
case "Date":
items = items.OrderBy(s => s.Date);
break;
case "date_desc":
items = items.OrderByDescending(s => s.Date);
break;
case "Extension":
items = items.OrderBy(s=>s.Extension);
break;
case "ext_desc":
items = items.OrderByDescending(s => s.Extension);
break;
default:
items = items.OrderBy(s => s.Name);
break;
}
return View(items);
}
Result:

ASP.NET passing List back to controller from IEnumerable #model inside Table header ActionLink with non-indexing

I have been reviewing possible ways to return a View's #model information which is of type IEnumerable back to the controller, so that if I sort/filter on a query from database, I can refine the return each iteration without restarting with a fresh full list being returned. All the ways show you need to POST back based on model[index] which works if you are inside a for loop. But I am working with sending the collection back from an #HTML.ActionLink within a table's header section, so there is no possible indexing available.
My WebAPI setup is based on this where they show how to sort and filter. I am trying to make it a little more complex in that after I filter a list based on my original DB query, I will then be able to sort (from a clickable-actionLink on a table's header column) from that filtered list; where as currently it would just sort from a fresh complete list.
The only way I can think of to do this is pass back (by a POST) to the controller the updated list of the customClass.
#Html.ActionLink("Name", "Index", new { orderBy = ViewBag.sortByName,
companyListIds = Model.???? })
A better option (based on comments from Tacud) which would require a smaller POST URL would be by returning a list of the id properties only which can then be applied to a query. But its still a list and still needs to be sent back without an index from and ActionLink. This will help keep track and allow me to continue drilling down to a smaller and smaller list.
Below is parts of my model class, the index Action from the controller, and the index view.
Model namespace:
public class Company
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
Controller Namespace:
public async Task<IActionResult> Index(ICollection<int> prev, string orderBy , string searchCategory ="", string searchString = "")
{
List<string> Categories = new List<string>() { "Name", "City", "State", "Zip", "Contact Person" };
ViewBag.searchCategory = new SelectList(Categories);
ViewBag.sortByName = orderBy == null ? "name" : orderBy == "name" ? "namedesc" : "name";
ViewBag.sortByCity = orderBy == "city" ? "citydesc" : "city";
ViewBag.sortByState = orderBy == "state" ? "statedesc" : "state";
ViewBag.companyIndex = companyList.Count==0 ? await _context.Company.ToListAsync() : companyList ;
List<Company> resultSet = new List<Company>(ViewBag.companyIndex);
if (!String.IsNullOrEmpty(searchCategory) && !String.IsNullOrEmpty(searchString))
{
switch (searchCategory)
{
.....
}
}
switch (orderBy)
{
....
}
return View(resultSet);
}
View namespace:
#model IEnumerable<Laier_It.Models.Company> <p>
#using (Html.BeginForm() {
<p>
Search By: #Html.DropDownList("SearchCategory", "")
Search For: #Html.TextBox("SearchString")
<input type="submit" value="Filter" />
</p> }
<table class="table ">
<thead>
<tr>
<th>
#Html.ActionLink("Name", "Index", new { orderBy = ViewBag.sortByName, companyList = Model })
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.ActionLink("City", "Index", new { orderBy = ViewBag.sortByCity, companyList = Model })
</th>
<th>
#Html.ActionLink("State", "Index", new { orderBy = ViewBag.sortByState, companyList = Model })
</th> </tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td> </tr>
}
</tbody>
</table>
To first obtain the list of Id's that I want to post back to the controller of the current rendition showing within the WebAPI view page I used #Model.Select(x => x.Id)
My controller index method was only changed by this
var resultSet = prev.Count == 0 ? await _context.Company.ToListAsync() :
await _context.Company.Where(x => prev.Contains(x.Id)).ToListAsync();
And my View looks like this:
#model IEnumerable<Laier_It.Models.Company>
#using (Html.BeginForm() )
{
<p>
Search By: #Html.DropDownList("SearchCategory", "")
Search For: #Html.TextBox("SearchString")
<input type="submit" value="Filter" />
</p>
}
<table class="table ">
<thead>
<tr>
<th>
#Html.ActionLink("Name", "Index", new { orderBy = ViewBag.sortByName, prev = #Model.Select(x => x.Id) } )
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.ActionLink("City", "Index", new { orderBy = ViewBag.sortByCity, prev = #Model.Select(x => x.Id) } )
</th>
<th>
#Html.ActionLink("State", "Index", new { orderBy = ViewBag.sortByState, prev = #Model.Select(x => x.Id) } )
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
</tr>
}
</tbody>
</table>

Approve/ Reject Method Not Work In asp.net mvc

I made a method for approving or rejecting registration requests from the user registration form.
When users submit a form, the request becomes pending and then admin has the authority to reject or approve the request; but my method does not work properly, because nothing happen.
The application just refresh the page when I click on the reject or approve button.
Can anyone tell me what's wrong with my code? Code snippets follow.
This is the approval controller
public class ApprovedRegistrationController :BaseAdminController
{
// GET: Admin/ApproveRegistration
public ActionResult Index(string Status)
{ ViewBag.Status = (Status == null ? "P" : Status);
if (Status == null)
{ var register = objBs.registerBs.GetALL().Where(x => x.Approved == "P").ToList();
return View(register); }
else
{ var register = objBs.registerBs.GetALL().Where(x => x.Approved == Status).ToList();
return View(register); }}
public ActionResult Approve(int id)
{ try
{ var myRegistration = objBs.registerBs.GetByID(id);
myRegistration.Approved = "A";
objBs.registerBs.Update(myRegistration);
TempData["Msg"] = "Approved Successfully";
return RedirectToAction("Index"); }
catch (Exception e1)
{ TempData["Msg"] = "Approved Failed: " + e1.Message;
return RedirectToAction("Index");}}
public ActionResult Reject(int id)
{try
{ var myRegistration = objBs.registerBs.GetByID(id);
myRegistration.Approved = "R";
objBs.registerBs.Update(myRegistration);
TempData["Msg"] = "Rejected Successfully";
return RedirectToAction("Index");}
catch (Exception e1)
{ TempData["Msg"] = "Rejection Failed: " + e1.Message;
return RedirectToAction("Index");}}}
Registration Approval or rejection view
#model IEnumerable<XtechWebsite.Models.Registration>
#{
ViewBag.Title = "Index";}
<h2>Index</h2>
<script>
function ConfirmApprove() {
return confirm('Are u sure to accept it?');
}
function ConfirmReject() {
return confirm('Are u sure to reject it?');
}
</script>
<h3>Manage Registration<h3>
#if (TempData["Msg"] != null)
{<h3 #TempData["Msg"].ToString()</h3>
}
<h4>#if (ViewBag.Status == "P")
{<b>#Html.ActionLink("Pending Requests", "Index", new { Status = "P" })</b>
}
else
{
#Html.ActionLink("Pending Requests", "Index", new { Status = "P" })
}
#if (ViewBag.Status == "A")
{
<b>#Html.ActionLink("Approved Requests", "Index", new { Status = "A" })</b>
}
else
{
#Html.ActionLink("Approved Requests", "Index", new { Status = "A" })
}
#if (ViewBag.Status == "R")
{
<b>#Html.ActionLink("Rejected Requests", "Index", new { Status = "R" })</b>
}
else
{
#Html.ActionLink("Rejected Requests", "Index", new { Status = "R" })
}
</h4
<table class="table">
<tr>
<th>Approve/Reject</th>
<th>
#Html.DisplayNameFor(model => model.First_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Last_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Department_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Team_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Select_Members)
</th>
<th>
#Html.DisplayNameFor(model => model.Approved)
</th>
<th>
#Html.DisplayNameFor(model => model.Email_ID)
</th>
<th>
#Html.DisplayNameFor(model => model.Competition.CategoryName)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink("Approve", "Approve", new { id = item.Registration_ID }, new { onclick = "return ConfirmApprove();" }) |
#Html.ActionLink("Reject", "Reject", new { id = item.Registration_ID }, new { onclick = "return ConfirmReject();" })
</td>
<td>
#Html.DisplayFor(modelItem => item.First_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Last_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Department_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Team_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Select_Members)
</td>
<td>
#Html.DisplayFor(modelItem => item.Approved)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Competition.CategoryName)
</td>
</tr> }
</table>
**Admin Base Contoller**
public class BaseAdminController : Controller
{
// GET: Admin/BaseAdmin
protected AdminBs objBs;
public BaseAdminController()
{
objBs = new AdminBs();
}
}
registerbs class that is used in approval controller
public class RegisterBs
{
private RegisterDb objDb;
public RegisterBs()
{
objDb = new RegisterDb();
}
public IEnumerable<Registration> GetALL()
{
return objDb.GetALL();
}
public Registration GetByID(int Id)
{
return objDb.GetByID(Id);
}
public void Insert(Registration registration)
{
objDb.Insert(registration);
}
public void Delete(int Id)
{
objDb.Delete(Id);
}
public void Update(Registration registration)
{
objDb.Update(registration);
}
}
<b>Registration db class<b>
public class RegisterDb
{
private XtechContext db;
public RegisterDb()
{
db= new XtechContext();
}
public IEnumerable<Registration> GetALL()
{
return db.Registrations.ToList();
}
public Registration GetByID(int Id)
{
return db.Registrations.Find(Id);
}
public void Insert(Registration registration)
{
db.Registrations.Add(registration);
Save();
}
public void Delete(int Id)
{
Registration registration = db.Registrations.Find(Id);
db.Registrations.Remove(registration);
Save();
}
public void Update(Registration registration)
{
db.Entry(registration).State = EntityState.Modified;
}
public void Save()
{
db.SaveChanges();
}
}
this is the interface pic then you easily understand it
You do not call SaveChanges on the context that why your modifications are not persisted to the database.
You may add a call to Save() in your update method.

I get this strange text on my view : System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince] System.Collections.Generic.HashSet

Greetings i get this a really strange messenge on the top of my view.
(System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince] System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince] )
I had a database and i use entinty first code made the connection. here is the model view im using:
public IEnumerable<ElencoOmonimi> elencoomonimi { get; set; }
public IEnumerable<ElencoProvince> elencoprovince { get; set; }
public IEnumerable<ElencoImmobiliPerDiritti_E_Quote> elencoimmobiliperditti { get; set; }
public IEnumerable<ElencoComuni> elencocomuni { get; set; }
public IEnumerable<ElencoIntestati> elencointestati { get; set; }
And the contollers:
public ActionResult Index(string searchString, int? id, int? courseID, int? idcom, int? elencoimo)
{
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.elencoimoobiliID = id.Value
return View(viewmodel);
}
And my view:
#model automasystem.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>
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.DisplayFor(modelItem => item.Provincia)
</td>
<td>
#Html.DisplayFor(modelItem => item.Fabbricati)
</td>
<td>
#Html.DisplayFor(modelItem => item.Terreni)
</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>
}
I don't understand why I get this for every record that its on the database:
System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince] System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince]
You have this in your view (embedded inside a <tr> but not within a <td> so it will actually show above the table!)
#if (item.ElencoProvinces != null)
{
#item.ElencoProvinces
}
That will try to output the string representation of that object, and the value of item.ElencoProvinces.ToString() is obviously
System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince]
If you don't want ElencoProvinces in your view, just remove those few lines. If you do want it then loop over the hashset, or pull specific information out of a particular item within it, and format it inside appropriate HTML.

How to pass Id from One View to Another MVC4

Problem:
I have List of Categories with SubCategories, so when i click on SubCategory item it redirect me to List of Entries. There along the list it has Create ActionLink. So the problem is passing the SubCategoryId when I click SubCategoryItem for the Create ActionLink. Without the CreateActionLink it lists the entries but with it, it gives an error in the index view:
Object reference not set to an instance of an object.
Line 6:
Line 7: <p>
Line 8: #Html.ActionLink("Create New", "Create", new { subCategoryId = #Model.SubCategoryId})
Line 9: </p>
Line 10:
I understand that i am passing null reference and the question is how to avoid that?
Here is my code:
Controller:
public class EntryController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult EntryList(int subCategoryId)
{
var entries = EntryDAL.GetEntries(subCategoryId);
return View("_EntryList",entries);
}
public ActionResult Create(int subCategoryId)
{
var model = new Entry();
model.SubCategoryId = subCategoryId;
return View(model);
}
[HttpPost]
public ActionResult Create(Entry entry)
{
try
{
if (ModelState.IsValid)
{
var add = EntryDAL.Add(entry);
return RedirectToAction("Index");
}
return View(entry);
}
catch (Exception)
{
return View();
}
}
}
IndexView:
#model PasswordCloud.Domain.Models.SubCategory
#{
ViewBag.Title = "Index";
}
<p>
#Html.ActionLink("Create New", "Create", new { subCategoryId = #Model.SubCategoryId })
</p>
#{Html.RenderPartial("_EntryList",Model.EntryList);}
PartialView:
#model IEnumerable<PasswordCloud.Domain.Models.Entry>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.Username)
</th>
<th>
#Html.DisplayNameFor(model => model.Password)
</th>
<th>
#Html.DisplayNameFor(model => model.Url)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.SubCategoryId)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Username)
</td>
<td>
#Html.DisplayFor(modelItem => item.Password)
</td>
<td>
#Html.DisplayFor(modelItem => item.Url)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.SubCategoryId)
</td>
<td>
#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>
SubCategoryListItem View:
#model IEnumerable<PasswordCloud.Domain.Models.SubCategory>
#foreach (var item in Model) {
#Html.ActionLink(item.Name,"Index","Entry", new { subCategoryId = item.SubCategoryId }, null)
}
In your Index action you never create a model and pass it to the view. So when it gets to your line where you make the action link where you use new { subCategoryId = #Model.SubCategoryId} your model is null. Thus you get a null ref exception. To fix it you need to do something like this.
public ActionResult Index()
{
var model = ...
return View(model);
}

Categories

Resources