I have a problem to show data from table "Building_Address" in view of "Lease_Status" - it shows no records - only column names as on the pic
The diagram of tables and relations is:
the code of cshtml:
#model IEnumerable<test_ent_frame.Models.Lease_Status>
#{
ViewBag.Title = "Index"; }
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create") </p> <table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Room_Details.number)
</th>
<th>
#Html.DisplayNameFor(model => model.Building_Address.City)
</th>
<th></th>
</tr>
#foreach (var item in Model) { <tr>
<td>
#Html.DisplayFor(modelItem => item.Room_Details.number)
</td>
<td>
#Html.DisplayFor(modelItem => item.Building_Address.City)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id_Lease }) |
#Html.ActionLink("Details", "Details", new { id = item.Id_Lease }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id_Lease })
</td> </tr> }
</table>
The code of controller:
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 test_ent_frame.Models;
namespace test_ent_frame.Controllers
{
public class Lease_StatusController : Controller
{
private testEntities db = new testEntities();
// GET: Lease_Status
public ActionResult Index()
{
var lease_Status = db.Lease_Status.Include(l => l.Room_Details);
return View(lease_Status.ToList());
}
// GET: Lease_Status/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Lease_Status lease_Status = db.Lease_Status.Find(id);
if (lease_Status == null)
{
return HttpNotFound();
}
return View(lease_Status);
}
// GET: Lease_Status/Create
public ActionResult Create()
{
ViewBag.Id_Room = new SelectList(db.Room_Details, "Id_Room", "Id_Room");
return View();
}
// POST: Lease_Status/Create
// Aby zapewnić ochronę przed atakami polegającymi na przesyłaniu dodatkowych danych, włącz określone właściwości, z którymi chcesz utworzyć powiązania.
// Aby uzyskać więcej szczegółów, zobacz https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id_Lease,Id_Room")] Lease_Status lease_Status)
{
if (ModelState.IsValid)
{
db.Lease_Status.Add(lease_Status);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Id_Room = new SelectList(db.Room_Details, "Id_Room", "Id_Room", lease_Status.Id_Room);
return View(lease_Status);
}
// GET: Lease_Status/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Lease_Status lease_Status = db.Lease_Status.Find(id);
if (lease_Status == null)
{
return HttpNotFound();
}
ViewBag.Id_Room = new SelectList(db.Room_Details, "Id_Room", "Id_Room", lease_Status.Id_Room);
return View(lease_Status);
}
// POST: Lease_Status/Edit/5
// Aby zapewnić ochronę przed atakami polegającymi na przesyłaniu dodatkowych danych, włącz określone właściwości, z którymi chcesz utworzyć powiązania.
// Aby uzyskać więcej szczegółów, zobacz https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id_Lease,Id_Room")] Lease_Status lease_Status)
{
if (ModelState.IsValid)
{
db.Entry(lease_Status).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Id_Room = new SelectList(db.Room_Details, "Id_Room", "Id_Room", lease_Status.Id_Room);
return View(lease_Status);
}
// GET: Lease_Status/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Lease_Status lease_Status = db.Lease_Status.Find(id);
if (lease_Status == null)
{
return HttpNotFound();
}
return View(lease_Status);
}
// POST: Lease_Status/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Lease_Status lease_Status = db.Lease_Status.Find(id);
db.Lease_Status.Remove(lease_Status);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
These are standard scaffolded files in visual studio
How to make it possible to show these records?
Debug:
Related
I have several Areas in my learning/demo app. In 'MyArea/Models' I have 'MyModel.cs'
When I try to add scaffolded item 'MVC controller with Views using EF' everything gets generated, I update database after that, but CRUD operations do not work when I start application. (When I add same Model but not in area everything is fine)
For example, nothing happens when I click link 'create new' on Index.
Can you please help me?
I'm expecting that I can use scaffolding items in ASP.NET Core MVC areas.
/area/partner/models
ticket.cs
namespace Website.Areas.Partner.Models
{
public class Ticket
{
public int Id { get; set; }
public string Title { get; set; }
}
}
/area/partner/controllers/
TicketsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Website.Areas.Partner.Models;
using Website.Data;
namespace Website.Areas.Partner.Controllers
{
[Area("Partner")]
[Authorize]
public class TicketsController : Controller
{
private readonly ApplicationDbContext _context;
public TicketsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Partner/Tickets
public async Task<IActionResult> Index()
{
return _context.Ticket != null ?
View(await _context.Ticket.ToListAsync()) :
Problem("Entity set 'ApplicationDbContext.Ticket' is null.");
}
// GET: Partner/Tickets/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null || _context.Ticket == null)
{
return NotFound();
}
var ticket = await _context.Ticket
.FirstOrDefaultAsync(m => m.Id == id);
if (ticket == null)
{
return NotFound();
}
return View(ticket);
}
// GET: Partner/Tickets/Create
public IActionResult Create()
{
return View();
}
// POST: Partner/Tickets/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Title")] Ticket ticket)
{
if (ModelState.IsValid)
{
_context.Add(ticket);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(ticket);
}
// GET: Partner/Tickets/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null || _context.Ticket == null)
{
return NotFound();
}
var ticket = await _context.Ticket.FindAsync(id);
if (ticket == null)
{
return NotFound();
}
return View(ticket);
}
// POST: Partner/Tickets/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Title")] Ticket ticket)
{
if (id != ticket.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(ticket);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TicketExists(ticket.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(ticket);
}
// GET: Partner/Tickets/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null || _context.Ticket == null)
{
return NotFound();
}
var ticket = await _context.Ticket
.FirstOrDefaultAsync(m => m.Id == id);
if (ticket == null)
{
return NotFound();
}
return View(ticket);
}
// POST: Partner/Tickets/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
if (_context.Ticket == null)
{
return Problem("Entity set 'ApplicationDbContext.Ticket' is null.");
}
var ticket = await _context.Ticket.FindAsync(id);
if (ticket != null)
{
_context.Ticket.Remove(ticket);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool TicketExists(int id)
{
return (_context.Ticket?.Any(e => e.Id == id)).GetValueOrDefault();
}
}
}
/area/partner/views/ticket
index.cshtml
#model IEnumerable<Website.Areas.Partner.Models.Ticket>
#{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-
id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-
id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
/data/
ApplicationDbContext
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Website.Models;
using Website.Areas.Partner.Models;
namespace Website.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.Property(e => e.FirstName)
.HasMaxLength(20);
modelBuilder.Entity<ApplicationUser>()
.Property(e => e.LastName)
.HasMaxLength(30);
}
public DbSet<LatestWork> LatestWork { get; set; } = default!;
public DbSet<Website.Areas.Partner.Models.Ticket> Ticket { get; set; } = default!;
}
}
I was missing Tag Helpers in views
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, AuthoringTagHelpers
I'm tring to make action that after each login user switch to Home Page.
But I need to switch in View/Car/Index. I try to put just path but it doesn't work. Any idea? Here is my AccountController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Automarket.Models;
using System.Data.Entity.Spatial;
namespace Automarket.Controllers
{
public class AccountController : Controller
{
// GET: Account
public ActionResult Index()
{
using (OurDBContext db = new OurDBContext())
{
return View(db.userAccount.ToList());
}
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(UserAccount account)
{
if (ModelState.IsValid)
{
using (OurDBContext db = new OurDBContext())
{
db.userAccount.Add(account);
db.SaveChanges();
}
ModelState.Clear();
ViewBag.Message = account.Firstname + " " + account.Lastname + "Succesfully Registered: ";
}
return View();
}
// Login method
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(UserAccount user)
{
using (OurDBContext db = new OurDBContext())
{
var usr = db.userAccount.Single(u => u.Username == user.Username && u.Password == user.Password);
if (usr != null)
{
Session["UserID"] = usr.Id.ToString();
Session["Username"] = usr.Username.ToString();
return RedirectToAction("Logged In ");
}
else
{
ModelState.AddModelError(" ", "Username or Password are incoorect");
}
}
return View();
}
public ActionResult LoggedIn()
{
if (Session["UserID"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(UserAccount account)
{
using (OurDBContext db = new OurDBContext())
if (ModelState.IsValid)
{
db.userAccount.Add(account);
return RedirectToAction("Index");
}
return View(account);
}
// List the details of user
public ActionResult Details(int id=0)
{
using (OurDBContext db = new OurDBContext())
{
UserAccount user = db.userAccount.Find(id);
if (user==null)
{
return HttpNotFound();
}
return View(user);
}
}
// post method for Delete User
public ActionResult Delete(int id =0)
{
using (OurDBContext db = new OurDBContext())
{
UserAccount user = db.userAccount.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
}
[HttpPost,ActionName("Delete")]
public ActionResult DeleteConfirmed(int id=0)
{
using (OurDBContext db = new OurDBContext())
{
UserAccount user = db.userAccount.Find(id);
if (user==null)
{
return HttpNotFound();
}
db.userAccount.Remove(user);
db.SaveChanges();
return RedirectToAction("Index");
}
}
public ActionResult Edit(int? id)
{
using (OurDBContext db = new OurDBContext())
{
if (id == null)
{
return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
}
UserAccount user = db.userAccount.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Firstname,Lastname,Email,Username,Password,ConfirmaPassword")] UserAccount user)
{
using (OurDBContext db = new OurDBContext())
if (ModelState.IsValid)
{
db.Entry(user).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
}
}
Index View:
#model IEnumerable<Automarket.Models.UserAccount>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Register")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Firstname)
</th>
<th>
#Html.DisplayNameFor(model => model.Lastname)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>
#Html.DisplayNameFor(model => model.Username)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Firstname)
</td>
<td>
#Html.DisplayFor(modelItem => item.Lastname)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.Username)
</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>
public ActionResult LoggedIn()
{
if (Session["UserID"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}
I think you'll have to put the name of the view that you want to show in "return View("nameOfViewHere")".
return RedirectToAction("Index", "Car");
You need to pass controllers name too as you calling from a different controller
I am having a problem with sorting and searching with datatables. The search box and arrows for sorting appear. When attempting to search or sort nothing happens and my code only shows 1 record when there is more than one.
Here is my code
The page with the table:
#model IEnumerable<WINCMUTest.Models.WINCMU_HostInfo>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table" id="thetables">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.IP_address)
</th>
<th>
#Html.DisplayNameFor(model => model.HostName)
</th>
<th>
#Html.DisplayNameFor(model => model.Zone)
</th>
<th></th>
</tr>
</thead>
#foreach (var item in Model)
{
<tbody>
<tr>
<td>
#Html.DisplayFor(modelItem => item.IP_address)
</td>
<td>
#Html.DisplayFor(modelItem => item.HostName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Zone)
</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>
</tbody>
}
</table>
My _Layout.cshtml page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
</div>
</div>
</div>
#RenderBody()
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#thetable').dataTable();
});
</script>
</body>
</html>
My Controller:
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 WINCMUTest.Models;
namespace WINCMUTest.Controllers
{
public class WINCMU_HostInfoController : Controller
{
private WINCMUEntities db = new WINCMUEntities();
// GET: WINCMU_HostInfo
public ActionResult Index()
{
return View(db.WINCMU_HostInfo.ToList());
}
// GET: WINCMU_HostInfo/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WINCMU_HostInfo wINCMU_HostInfo = db.WINCMU_HostInfo.Find(id);
if (wINCMU_HostInfo == null)
{
return HttpNotFound();
}
return View(wINCMU_HostInfo);
}
// GET: WINCMU_HostInfo/Create
public ActionResult Create()
{
return View();
}
// POST: WINCMU_HostInfo/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 = "IP_address,HostName,Zone,ID")] WINCMU_HostInfo wINCMU_HostInfo)
{
if (ModelState.IsValid)
{
db.WINCMU_HostInfo.Add(wINCMU_HostInfo);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(wINCMU_HostInfo);
}
// GET: WINCMU_HostInfo/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WINCMU_HostInfo wINCMU_HostInfo = db.WINCMU_HostInfo.Find(id);
if (wINCMU_HostInfo == null)
{
return HttpNotFound();
}
return View(wINCMU_HostInfo);
}
// POST: WINCMU_HostInfo/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 = "IP_address,HostName,Zone,ID")] WINCMU_HostInfo wINCMU_HostInfo)
{
if (ModelState.IsValid)
{
db.Entry(wINCMU_HostInfo).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(wINCMU_HostInfo);
}
// GET: WINCMU_HostInfo/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WINCMU_HostInfo wINCMU_HostInfo = db.WINCMU_HostInfo.Find(id);
if (wINCMU_HostInfo == null)
{
return HttpNotFound();
}
return View(wINCMU_HostInfo);
}
// POST: WINCMU_HostInfo/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
WINCMU_HostInfo wINCMU_HostInfo = db.WINCMU_HostInfo.Find(id);
db.WINCMU_HostInfo.Remove(wINCMU_HostInfo);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
You've got the tags inside the foreach loop, move them outside. – markpsmith
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 WINCMUTest.Models;
namespace WINCMUTest.Controllers
{
public class WINCMU_HostInfoController : Controller
{
private WINCMUEntities db = new WINCMUEntities();
// GET: WINCMU_HostInfo
public ActionResult Index()
{
return View(db.WINCMU_HostInfo.ToList());
}
// GET: WINCMU_HostInfo/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WINCMU_HostInfo wINCMU_HostInfo = db.WINCMU_HostInfo.Find(id);
if (wINCMU_HostInfo == null)
{
return HttpNotFound();
}
return View(wINCMU_HostInfo);
}
// GET: WINCMU_HostInfo/Create
public ActionResult Create()
{
return View();
}
// POST: WINCMU_HostInfo/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 = "IP_address,HostName,Zone,ID")] WINCMU_HostInfo wINCMU_HostInfo)
{
if (ModelState.IsValid)
{
db.WINCMU_HostInfo.Add(wINCMU_HostInfo);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(wINCMU_HostInfo);
}
// GET: WINCMU_HostInfo/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WINCMU_HostInfo wINCMU_HostInfo = db.WINCMU_HostInfo.Find(id);
if (wINCMU_HostInfo == null)
{
return HttpNotFound();
}
return View(wINCMU_HostInfo);
}
// POST: WINCMU_HostInfo/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 = "IP_address,HostName,Zone,ID")] WINCMU_HostInfo wINCMU_HostInfo)
{
if (ModelState.IsValid)
{
db.Entry(wINCMU_HostInfo).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(wINCMU_HostInfo);
}
// GET: WINCMU_HostInfo/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WINCMU_HostInfo wINCMU_HostInfo = db.WINCMU_HostInfo.Find(id);
if (wINCMU_HostInfo == null)
{
return HttpNotFound();
}
return View(wINCMU_HostInfo);
}
// POST: WINCMU_HostInfo/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
WINCMU_HostInfo wINCMU_HostInfo = db.WINCMU_HostInfo.Find(id);
db.WINCMU_HostInfo.Remove(wINCMU_HostInfo);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
So essentially I've done all my sorting, filtering and paging with the help of this tutorial, which has been very, very handy because I'm very new to this material. -
http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
The Controller:
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 SunsUniversity.Models;
using SunsUniversity.DAL;
using PagedList;
using PagedList.Mvc;
namespace SunsUniversity.Controllers
{
public class StudentController : Controller
{
private SchoolContext db = new SchoolContext();
// GET: /Student/
public ViewResult Index()
{
var students = from s in db.Students
select s;
return View(students.ToList());
}
// GET: /Student/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
// GET: /Student/Create
public ActionResult Create()
{
return View();
}
// POST: /Student/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,LastName,FirstMidName,EnrollmentDate")] Student student)
{
try
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(student);
}
// GET: /Student/Edit/5
public ActionResult Edit(int? id)
{
var model = TempData["Index"];
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
// POST: /Student/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,LastName,FirstMidName,EnrollmentDate")] Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
// GET: /Student/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
// POST: /Student/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Student student = db.Students.Find(id);
db.Students.Remove(student);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
The Index:
#model IEnumerable<SunsUniversity.Models.Student>
#{
ViewBag.Title = "Students";
}
<h2>#ViewBag.Title</h2>
<p class="indexOptions">
#Html.ActionLink("Back", "Index", "Home") #Html.ActionLink("Create New", "Create")
</p>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.LastName)
</th>
<th>
#Html.DisplayNameFor(model => model.FirstMidName)
</th>
<th>
#Html.DisplayNameFor(model => model.EnrollmentDate)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstMidName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EnrollmentDate)
</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>
}
</tbody>
<tfoot>
<tr>
<th class="filterable"></th>
<th></th>
<th class="filterable"></th>
<th class="filterable"></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
#section Outro{
<script>
$(document).ready(function () {
var table = $('.table').DataTable();
$(".table tfoot th").each(function (i) {
if ($(this).hasClass("filterable")) {
var select = $('<select class="form-control"><option value="">Filter by</option></select>')
.appendTo($(this).empty())
.on('change', function () {
var val = $(this).val();
table.column(i)
.search(val ? '^' + $(this).val() + '$' : val, true, false)
.draw();
});
table.column(i).data().unique().sort().each(function (d, j) {
if (d.length > 0) {
select.append('<option value="' + d + '">' + d + '</option>');
}
});
}
});
});
</script>
}
Now my problem is:
My application users asked if it were possible for pages that contain a table to remember the filter, sort order and current page of the table(because when they click a table item to carry out a task and then go back to it they'd like it to be "as they left it")
Cookies seem to be the way forward, but how to get the page to load these and set them in the table before it makes its first data request is a little beyond me at this stage.
Does anyone have any experience with this kind of thing? Thanks!
Few things can be added at the end in the Index file
Save Preferences : called from $(window).unload(function(){ ... });
Load Preferences : called from $(document).ready(function(){ ... });
The easiest way would be to save the filters, ordering and page you want to go to in the session storage, a cookie, or viewbag. You would send the parameters on all calls back to the server on back to page. EF doesn't support the operation you want as it only cares about getting and setting data. You have to manage the pagination, sorting, and filtering in YOUR code.
The example you refer to handles this by using these parameters of PagedList( a nuget package)
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
The parameters are what they say they are and are sent back on each page you navigate to.
Full method code:
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var students = from s in db.Students
select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.LastName.Contains(searchString)
|| s.FirstMidName.Contains(searchString));
}
switch (sortOrder)
{
case "name_desc":
students = students.OrderByDescending(s => s.LastName);
break;
case "Date":
students = students.OrderBy(s => s.EnrollmentDate);
break;
case "date_desc":
students = students.OrderByDescending(s => s.EnrollmentDate);
break;
default: // Name ascending
students = students.OrderBy(s => s.LastName);
break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(students.ToPagedList(pageNumber, pageSize));
}
I build alittke website using c# razor.
I have a model class named "clientModel".
I used crud operation using entity framework.
at first, evrything worked fine .
But when I changed the primary key of the clientModel class from "tracingNumber" to "emailAdress" I can't delete and edit the db from the website.
when I try to do this I get HTTP Error 404.0 - Not Found.
any idea??
controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VicoProject___NewVersion.Models;
namespace Project___NewVersion.Controllers
{
public class ClientController : Controller
{
private ClientModelsDBContext db = new ClientModelsDBContext();
//
// GET: /Model/
public ActionResult Index()
{
return View(db.Clients.ToList());
}
//
// GET: /Model/Details/5
public ActionResult Details(int id = 0)
{
ClientModels clientmodels = db.Clients.Find(id);
if (clientmodels == null)
{
return HttpNotFound();
}
return View(clientmodels);
}
//
// GET: /Model/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Model/Create
[HttpPost]
public ActionResult Create(ClientModels clientmodels)
{
if (ModelState.IsValid)
{
db.Clients.Add(clientmodels);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(clientmodels);
}
//
// GET: /Model/Edit/5
public ActionResult Edit(int id = 0)
{
ClientModels clientmodels = db.Clients.Find(id);
if (clientmodels == null)
{
return HttpNotFound();
}
return View(clientmodels);
}
//
// POST: /Model/Edit/5
[HttpPost]
public ActionResult Edit(ClientModels clientmodels)
{
if (ModelState.IsValid)
{
db.Entry(clientmodels).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(clientmodels);
}
//
// GET: /Model/Delete/5
public ActionResult Delete(int id = 0)
{
ClientModels clientmodels = db.Clients.Find(id);
if (clientmodels == null)
{
return HttpNotFound();
}
return View(clientmodels);
}
//
// POST: /Model/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
ClientModels clientmodels = db.Clients.Find(id);
db.Clients.Remove(clientmodels);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
public ActionResult Search(string search)
{
var r = db.Clients.Where(t => t.emailAdress.Contains(search) || t.name.Contains(search)).ToList();
Console.Write(r);
return RedirectToAction("Search");
}
}
}
client model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace Project___NewVersion.Models
{
public class ClientModels
{
[Required]
public string name { get; set;}
[Required]
[MaxLength(10, ErrorMessage = "Phone Number must be 10 numbers") , MinLength(10, ErrorMessage = "Phone Number must be 10 numbers")]
[DataType(DataType.PhoneNumber, ErrorMessage = "Invalid Phone Number")]
public String phoneNumber { get; set; }
[Key]
[Required]
[DataType(DataType.EmailAddress, ErrorMessage = "Invalid Email Address")]
public string emailAdress { get; set; }
}
public class ClientModelsDBContext : DbContext
{
static ClientModelsDBContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ClientModelsDBContext>());
}
public DbSet<ClientModels> Clients { get; set; }
}
}
the client/index view:
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.name)
</th>
<th>
#Html.DisplayNameFor(model => model.phoneNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.emailAdress)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td>
#Html.DisplayFor(modelItem => item.phoneNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.emailAdress)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.emailAdress }) |
#Html.ActionLink("Details", "Details", new { id=item.emailAdress }) |
#Html.ActionLink("Delete", "Delete", new { id=item.emailAdress})
</td>
</tr>
}
</table>
The function with the signature
public ActionResult Delete(int id = 0)
needs to be called. The parameter to this is an int. I assume since changing it the id is now a string - so the framework doesn't know which method to call.