MVC中的CRUD操作5

时间:2014-05-21 06:27:02

标签: asp.net asp.net-mvc visual-studio-2013 asp.net-mvc-5

我正在开发MVC 5中的应用程序并对其执行CRUD操作。

我已成功将Northwind数据库添加为实体数据模型,并在模型中引入了客户。现在在Scaffolding的帮助下,我生成了CustomersController。

当我在客户表中创建新记录时。没问题。

但是当我点击该新记录时,编辑,详细信息和删除功能无法正常工作。点击其中任何一个后:

enter image description here

出现以下页面:

enter image description here

我的控制器代码:

namespace MvcNorthwindSample.Controllers
{

    public class CustomersController : Controller
    {
        private NORTHWNDEntities db = new NORTHWNDEntities();

        // GET: Customers
        public ActionResult Index()
        {
            return View(db.Customers.ToList());
        }

        // GET: Customers/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                return HttpNotFound();
            }
            return View(customer);
        }

        // GET: Customers/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Customers/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 = "CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
        {
            if (ModelState.IsValid)
            {
                db.Customers.Add(customer);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(customer);
        }

        // GET: Customers/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                return HttpNotFound();
            }
            return View(customer);
        }

        // POST: Customers/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 = "CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
        {
            if (ModelState.IsValid)
            {
                db.Entry(customer).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(customer);
        }

        // GET: Customers/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                return HttpNotFound();
            }
            return View(customer);
        }

        // POST: Customers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            Customer customer = db.Customers.Find(id);
            db.Customers.Remove(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

我的观点部分:

enter image description here

调试时

我的创建代码结果视图:

enter image description here

5 个答案:

答案 0 :(得分:1)

编辑:发布控制器后

Customer customer = db.Customers.Find(id);
if (customer == null)
{
    return HttpNotFound();
}

你确定你有一个id为1994的客户吗?因为你的逻辑会以其他方式返回HttpNotFound()

在您发布的屏幕截图中。我可以阅读HTTP 404错误消息,并且尝试访问请求的网址/Customer/Edit/1994

因此我认为你必须拥有以下控制器/动作。

public class CustomerController
{
    public ActionResult Edit(int id)
    {
        return View();
    }
}

现在大多数人(包括我)最常犯的错误是将变量命名为id

这需要将id命名为默认路由,除非如此。

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

但是有一种解决方法,如果您不希望将变量命名为id,则表示您希望将其命名为year,然后您的网址应为/Customer/Edit?year=1994,这将有效。< / p>

答案 1 :(得分:0)

错误是404错误。

它正在向控制器Customers查找Edit操作。

在评论中也指出,Id 1994有一个编码空格字符。如果id被认为是字符串,则可以将参数更改为键入string而不是int

public class CustomersController
{
    public ActionResult Edit(int id)
    {
        return View();
    }
}

答案 2 :(得分:0)

我解决了。我终于换了桌子。名为Customers的Northwind数据库的表上存在问题。我下载数据库备份文件。 “客户ID”列将使用插入的值添加空格作为默认值。

答案 3 :(得分:0)

首先创建模型和Dbcontext。

public class TaskManagerContext : DbContext
{
    public TaskManagerContext()
        : base("TaskManagerDB")
    {

    }

    public DbSet<User> Users { get; set; }
    public DbSet<Task> Tasks { get; set; }
}

然后允许迁移并从PM更新数据库。创建一个文件夹,其中包含其余必须继承的BaseRepo。

public class BaseRepository<T> where T:BaseModel, new()
{
    protected TaskManagerContext context;
    protected DbSet<T> dbSet;

    public BaseRepository()
    {
        this.context = new TaskManagerContext();
        this.dbSet = this.context.Set<T>();
    }

    public void Insert(T item)
    {
        this.dbSet.Add(item);
        this.context.SaveChanges();
    }

    public void Update(T item)
    {
        this.context.Entry(item).State = EntityState.Modified;
        this.context.SaveChanges();
    }

    public void Delete(int id)
    {
        this.dbSet.Remove(this.dbSet.Find(id));
        this.context.SaveChanges();
    }

    public IEnumerable<T> GetAll()
    {
        return this.dbSet;
    }
}
像这样:

public class UsersRepository : BaseRepository<User>
{
    public UsersRepository()
        : base()
    {
    }
}

然后创建使用repos中方法的控制器。

public class UsersController : Controller
{
    //
    // GET: /Users/
    public ActionResult List()
    {
        List<User> users = new List<User>();
        users = new UsersRepository().GetAll().ToList();
        return View(users);
    }

    public ActionResult Edit(int id)
    {
        User user = new UsersRepository().GetAll().FirstOrDefault(u => u.ID == id);
        return View(user);
    }

    [HttpPost]
    public ActionResult Edit(User user)
    {
        UsersRepository repo = new UsersRepository();
        repo.Update(user);
        return RedirectToAction("List");
    }

    public ActionResult Delete(int id)
    {
        UsersRepository repo = new UsersRepository();
        repo.Delete(id);
        return RedirectToAction("List");
    }

    public ActionResult Create()
    {
        User u = new User();
        return View(u);
    }

    [HttpPost]
    public ActionResult Create(User user)
    {
        UsersRepository repo = new UsersRepository();
        repo.Insert(user);

        return RedirectToAction("List");
    }
}

TaskContr的操作是simillar执行List,您可以通过ID连接2个模型:

public ActionResult List(int? id)
    {
        TasksRepository repo = new TasksRepository();
        List<Task> tasks = new List<Task>();

        tasks = repo.GetAll().Where(t => t.UserID == id).ToList();
        return View(tasks);
    }

不要忘记生成视图(在Get方法上)并更改用户的列表视图:

 @Html.ActionLink("Details", "List", "Tasks", new { id=item.ID }, null) |

单击详细信息时,您可以看到该用户的任务。

答案 4 :(得分:0)

  public ActionResult Index()
        {

            using (DevExam db = new DevExam())
            {

                var intern = from m in db.Interns 
                             select m;


                return View(intern.ToList());
            }

           /* using (DevExam db = new DevExam())
            {
                var interns = db.Interns
                     .Include(s => s.InternID)
                     .Select(s => new Intern
                     {
                     InternID = s.InternID,
                     lname = s.lname,
                     fname = s.fname 
                     });
                return View(interns);
             }
             */
        }

        // GET: CRUD/Details/5
        public ActionResult Details(int id)
        {
            using (DevExam db = new DevExam())
            {
                return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
            }
        }

        // GET: CRUD/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: CRUD/Create
        [HttpPost]
        public ActionResult Create(Intern intern)
        {
            try
            {
                // TODO: Add insert logic here
                using (DevExam db = new DevExam())
                {
                    db.Interns.Add(intern);
                    db.SaveChanges();
                }

                    return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: CRUD/Edit/5
        public ActionResult Edit(int id)
        {
            using (DevExam db = new DevExam())
            {
                return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
            }
        }

        // POST: CRUD/Edit/5
        [HttpPost]
        public ActionResult Edit(int id,Intern intern)
        {
            try
            {
                // TODO: Add update logic here

                using (DevExam db = new DevExam())
                {
                    db.Entry(intern).State = EntityState.Modified;
                    db.SaveChanges();
                }

                    return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: CRUD/Delete/5
        public ActionResult Delete(int id)
        {
            using (DevExam db = new DevExam())
            {
                return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
            }
        }

        // POST: CRUD/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
                using (DevExam db = new DevExam())
                {
                    Intern intern = db.Interns.Where(x => x.InternID == id).FirstOrDefault();
                    db.Interns.Remove(intern);
                    db.SaveChanges();
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }