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);
}
}
}
Related
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:
actually I can not want to visible my id when I was something delete.so I want to slug here.but can not understand how I modify or convert id to slug type.
here is my code:
startup.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area=Customer}/{controller=Home}/{action=Index}/{id?}"
);
});
[HttpGet]
public ActionResult Delete(int? id)
{
if (id == null)
{
NotFound();
}
var product = _db.Spray.Include(c => c.ProductTypes).FirstOrDefault(c => c.Id == id);
if (product == null)
{
return NotFound();
}
return View(product);
}
[HttpPost]
[ActionName("Delete")] //DeleteConfirm nam ke delete namei chinbo
public async Task<IActionResult> DeleteConfirm(int? id)
{
if (id == null)
{
return NotFound();
}
var product = _db.Spray.FirstOrDefault(c => c.Id == id);
if (product == null)
{
return NotFound();
}
_db.Spray.Remove(product);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}
Delete.cshtml
form asp-action="Delete" method="post" enctype="multipart/form-data">
<div class="p-4 rounded border-row">
<div asp-validation-summary="ModelOnly" class="text-danger">
</div>
<div>
<div class="col-8">
<div class="form-group row">
<div class="col-4">
<label asp-for="Name"></label>
</div>
<div class="col-8">
<input type="hidden" asp-for="Id" />
<input asp-for="Name" readonly="readonly" class="form-control" />
</div>
<span asp-validation-for="Name" class="text-danger"></span>
</div>
I have no idea to add how to add slug. I don't want to see my visible id for that I tried to make its slug. but I don't understand actually how to take process. I am beginner, please help anyone.
It seems you want to make id unvisible in the url, the simple way is to change Delete action to the post type.
Index.cshtml:
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<form method="post" asp-action="Delete" asp-controller="Sprays">
<input type="hidden" value="#item.Id" name="id" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
}
</tbody>
</table>
Controller:
[HttpPost]
public ActionResult Delete(int? id)
{
//..
}
[HttpPost]
//[ActionName("Delete")]
public async Task<IActionResult> DeleteConfirm(int? id)
{
//...
}
Be sure your Delete.cshtml should be like below:
<form asp-action="DeleteConfirm" method="post" enctype="multipart/form-data">
Result:
Update:
Index.cshtml:
<form method="post" asp-action="Delete" asp-controller="Sprays" asp-route-slug="my-delete-id">
<input type="hidden" value="#item.Id" name="id" />
<input type="submit" value="Delete" />
</form>
Controller:
[HttpPost]
public async Task<IActionResult> Delete(string slug)
{
var data = HttpContext.Request.Form["id"].First();
var id = int.Parse(data);
//...
}
[HttpPost]
//[ActionName("Delete")]
public async Task<IActionResult> DeleteConfirm(int? id)
{
//...
}
Startup.cs:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{slug?}");
});
Result:
Whole Controller:
public class TestsController : Controller
{
private readonly MyDbContext _context;
public TestsController(MyDbContext context)
{
_context = context;
}
// GET: Tests
public async Task<IActionResult> Index()
{
return View(await _context.Test.ToListAsync());
}
// GET: Tests/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var test = await _context.Test
.FirstOrDefaultAsync(m => m.Id == id);
if (test == null)
{
return NotFound();
}
return View(test);
}
// GET: Tests/Create
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name")] Test test)
{
if (ModelState.IsValid)
{
_context.Add(test);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(test);
}
// GET: Tests/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var test = await _context.Test.FindAsync(id);
if (test == null)
{
return NotFound();
}
return View(test);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] Test test)
{
if (id != test.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(test);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TestExists(test.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(test);
}
[HttpPost]
public async Task<IActionResult> Delete(string slug)
{
var data = HttpContext.Request.Form["id"].First();
var id = int.Parse(data);
var test = await _context.Test
.FirstOrDefaultAsync(m => m.Id == id);
if (test == null)
{
return NotFound();
}
return View(test);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var test = await _context.Test.FindAsync(id);
_context.Test.Remove(test);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool TestExists(int id)
{
return _context.Test.Any(e => e.Id == id);
}
}
Whole Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDbContext")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{slug?}");
});
}
I am trying to make a web store application and in this case I am using video games as an example. I made a model class for a Video Game called VideoGame.cs which would be located in the Models folder of my ASP.NET MVC project. This class looks like:
namespace VideoGameStore.Models
{
public class VideoGame
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
public class VideoGameDBContext : DbContext
{
public DbSet<VideoGame> VideoGames { get; set; }
}
}
I used EF Scaffolding to make a controller called VideoGamesController.cs located in the Controllers folder of my project. I thought of using this controller in such a way that an user with administrator role could add new, remove and update video games to this store. This is how my controller looks like:
namespace VideoGameStore.Controllers
{
public class VideoGamesController : Controller
{
private VideoGameDBContext db = new VideoGameDBContext();
// GET: VideoGames
public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.TitleSortParm = String.IsNullOrEmpty(sortOrder) ? "title_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if(searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var videoGames = from v in db.VideoGames
select v;
if(!String.IsNullOrEmpty(searchString))
{
videoGames = videoGames.Where(s => s.Title.Contains(searchString) || s.Description.Contains(searchString));
}
switch(sortOrder)
{
case "title_desc":
videoGames = videoGames.OrderByDescending(s => s.Title);
break;
case "Date":
videoGames = videoGames.OrderBy(s => s.ReleaseDate);
break;
case "date_desc":
videoGames = videoGames.OrderByDescending(s => s.ReleaseDate);
break;
default:
videoGames = videoGames.OrderBy(s => s.Title);
break;
}
int pageSize = 20;
int pageNumber = (page ?? 1);
return View(videoGames.ToPagedList(pageNumber, pageSize));
}
// GET: VideoGames/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
VideoGame videoGame = db.VideoGames.Find(id);
if (videoGame == null)
{
return HttpNotFound();
}
return View(videoGame);
}
[Authorize(Roles="Admin")]
// GET: VideoGames/Create
public ActionResult Create()
{
return View();
}
[Authorize(Roles="Admin")]
// POST: VideoGames/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,Title,ReleaseDate,Genre,Description,Price")] VideoGame videoGame)
{
if (ModelState.IsValid)
{
db.VideoGames.Add(videoGame);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(videoGame);
}
[Authorize(Roles="Admin")]
// GET: VideoGames/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
VideoGame videoGame = db.VideoGames.Find(id);
if (videoGame == null)
{
return HttpNotFound();
}
return View(videoGame);
}
[Authorize(Roles="Admin")]
// POST: VideoGames/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,Title,ReleaseDate,Genre,Description,Price")] VideoGame videoGame)
{
if (ModelState.IsValid)
{
db.Entry(videoGame).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(videoGame);
}
[Authorize(Roles="Admin")]
// GET: VideoGames/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
VideoGame videoGame = db.VideoGames.Find(id);
if (videoGame == null)
{
return HttpNotFound();
}
return View(videoGame);
}
[Authorize(Roles="Admin")]
// POST: VideoGames/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
VideoGame videoGame = db.VideoGames.Find(id);
db.VideoGames.Remove(videoGame);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
And finally I would be having a View in which the project would display the user a collection of videogames available in the store (and if the user would be an administrator, the collection could be managed on this view aswell). The view called Index.cshtml located in the Views/VideoGames folder would look like this:
#model PagedList.IPagedList<VideoGameStore.Models.VideoGame>
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Video Games Store";
}
<h2>Video Games Store</h2>
#if (User.Identity.IsAuthenticated)
{
if (User.IsInRole("Admin"))
{
<p>
#Html.ActionLink("Create New", "Create")
</p>
}
}
#using(Html.BeginForm("Index", "VideoGames", FormMethod.Get))
{
<p>
#Html.TextBox("searchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" />
</p>
}
<div class="row">
#foreach (var item in Model) {
<div class="col-md-3">
#Html.DisplayFor(modelItem => item.Title)<br />
#Html.DisplayFor(modelItem => item.Genre)<br />
€#Html.DisplayFor(modelItem => item.Price)<br />
#if (User.Identity.IsAuthenticated)
{
if(User.IsInRole("Admin"))
{
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) <text> | </text>
}
}
#Html.ActionLink("Details", "Details", new { id=item.Id })
#if (User.Identity.IsAuthenticated)
{
if (User.IsInRole("Admin"))
{
<text> | </text> #Html.ActionLink("Delete", "Delete", new { id = item.Id })
}
}
<br />
#Html.ActionLink("Add to cart", "AddToCart", new { controller = "ShoppingCart", id = item.Id })
</div>
}
</div>
<div class="row">
<div class="col-md-12">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
</div>
</div>
Currently I would like to add some code so that once a user clicks on the #Html.ActionLink("Add to cart", "AddToCart", new { controller = "ShoppingCart", id = item.Id }) the user would be able to add the desired item to the shopping cart. I thought of adding a new controller called ShoppingCartController.cs to handle Shopping Cart processing and that is why I added it to the ActionLink HTML helper in the view. This is how the ShoppingCartController.cs looks like:
namespace VideoGameStore.Controllers
{
public class ShoppingCartController : Controller
{
// GET: ShoppingCart
public ActionResult Index()
{
return View();
}
public ActionResult AddToCart(int Id)
{
//What code could I add here?
return RedirectToAction("Index");
}
}
}
I have been reading that using session in MVC for making a shopping cart would not be an ideal way to solve this. Would I have to add a ShoppingCart model to my project and store the shopping cart data in a database (and if so, how could I make this look like)? I also read that I would not want a user to store data on a HTTP GET Request, but I would not want the user having to post their decision to add an item to the shopping cart on a different page over again. How could I adjust my ShoppingCartController.cs?
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
This is homework, and I looked up similar questions, but I'm too code-challenged to know exactly how the syntax should be from the examples. This is an ASP.NET MVC app in Visual Studio, C#. This is what I get when I run it.
When I click on "Edit" or "Details" I want it to go to a page where a bike can be edited or details entered. Right now, it's going to the original assignment's index page, which has nothing to do with this, but the professor wants all of our assignments in one project:
Here is my BikeController code:
using MvcApplication3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication3.Controllers
{
public class BikeController : Controller
{
//
// GET: /Bike/
List<Bike> bikes;
public BikeController()
{
if (bikes == null)
{
bikes = new List<Bike> {
new Bike(),
new Bike { Manufacturer = "Nishiki", Gears = 5, Frame = "Road" }
};
}
}
public ActionResult Index()
{
return View(this.bikes);
}
private ActionResult View(Func<object> func)
{
throw new NotImplementedException();
}
//
// GET: /Bike/Details/5
public ActionResult Details(int id)
{
var currentBikes = bikes[id];
return View(currentBikes);
}
//
// GET: /Bike/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Bike/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
Bike b = new Bike
{
Manufacturer = collection["Manufacturer"], Gears = int.Parse(collection["Gears"]), Frame = collection["Frame"]
};
bikes.Add(b);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Bike/Edit/5
public ActionResult Edit(int id)
{
return View(bikes.Where(b => b.BikeID == id).First());
}
//
// POST: /Bike/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Bike/Index");
}
catch
{
return View();
}
}
//
// GET: /Bike/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /Bike/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public int bike { get; set; }
}
}
Here is the Index in the Bike View:
#model IEnumerable<MvcApplication3.Models.Bike>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Manufacturer)
</th>
<th>
#Html.DisplayNameFor(model => model.Gears)
</th>
<th>
#Html.DisplayNameFor(model => model.Frame)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Manufacturer)
</td>
<td>
#Html.DisplayFor(modelItem => item.Gears)
</td>
<td>
#Html.DisplayFor(modelItem => item.Frame)
</td>
<td>
#item.BikeID #item.Manufacturer #item.Gears #item.Frame
#Html.ActionLink("Edit", "Edit", new { id=item.BikeID }) |
#Html.ActionLink("Details", "Details", new { id=item.BikeID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.BikeID })
</td>
</tr>
}
</table>
</body>
</html>
You are never setting your BikeID, this needs to be unique
Also i'm have not sure what this is for
public int bike { get; set; }
in your BikeController try explicitly setting the id's
new Bike() { BikeID = 1},
new Bike { Manufacturer = "Nishiki", Gears = 5, Frame = "Road", BikeID = 2 }
Also check your routing, in Global.asax there will
make sure routing is set up, this should be in either your global.asax or App_Start/RouteConfig.cs
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }