尝试使用 EntityFramework 添加具有读/写操作的 MVC 控制器。我的控制器名称是 UsersController。当我点击添加时,VS 会创建一个名为 Users 的文件夹和子目录,如 Create、Edit、Index 等。
我的实体模型表名称是用户。
当我尝试通过下面的链接联系他们时,我收到“找不到资源 404”错误。
http://localhost:64871/Users <br>
http://localhost:64871/Users/Index<br>
http://localhost:64871/Users/Create
我可以访问使用空 MVC 控制器选项创建的链接。
http://localhost:64871/Home<br>
http://localhost:64871/Home/Test
有什么问题?我应该在我的 RouteConfig 文件中添加一些值吗?
我的 RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我的用户控制器看起来像;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Aplatform.Controllers
{
public class UsersController : Controller
{
private dbEntities db = new dbEntities();
//
// GET: /Users/
public ActionResult Index()
{
return View(db.Users.ToList());
}
//
// GET: /Users/Details/5
public ActionResult Details(Guid id = null)
{
Users users = db.Users.Find(id);
if (users == null)
{
return HttpNotFound();
}
return View(users);
}
//
// GET: /Users/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Users/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Users users)
{
if (ModelState.IsValid)
{
users.ID = Guid.NewGuid();
db.Users.Add(users);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(users);
}
//
// GET: /Users/Edit/5
public ActionResult Edit(Guid id = null)
{
Users users = db.Users.Find(id);
if (users == null)
{
return HttpNotFound();
}
return View(users);
}
//
// POST: /Users/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Users users)
{
if (ModelState.IsValid)
{
db.Entry(users).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(users);
}
//
// GET: /Users/Delete/5
public ActionResult Delete(Guid id = null)
{
Users users = db.Users.Find(id);
if (users == null)
{
return HttpNotFound();
}
return View(users);
}
//
// POST: /Users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(Guid id)
{
Users users = db.Users.Find(id);
db.Users.Remove(users);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
谢谢!