【问题标题】:CRUD Operations in MVC 5MVC 5 中的 CRUD 操作
【发布时间】:2014-07-09 15:27:37
【问题描述】:

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

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

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

但是当我点击那条新记录时,编辑、详细信息和删除都不起作用。点击其中任何一个后:

出现以下页面:

我的控制器代码:

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);
        }
    }
}

我的视图部分:

调试时我的创建代码结果视图:

【问题讨论】:

  • 您的网址中的 id 后面似乎有一个空格字符 (%20)。这是故意的吗?
  • @JLRishe 感谢您的回复。我不会在任何地方插入空格字符。
  • 嗯,它被添加到某个地方。向我们展示您的相关代码(控制器和视图)。如果您不向我们提供任何信息,我们将无法解决您的问题。
  • @Yasser 我已经提到我使用带有视图的实体框架通过脚手架生成了我的控制器
  • @NimitJoshi 你介意分享一下吗?

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


【解决方案1】:

编辑:发布控制器后:

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

您确定有一位客户的 id 是 1994 年吗?如果不是,您的逻辑将返回 HttpNotFound()

在您发布的屏幕截图中,我可以看到HTTP 404 错误消息,请求的URL 是/Customer/Edit/1994

因此,我假设您必须具有以下控制器/操作:

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

现在大多数人(包括我)最常犯的错误是在 URL 中正确传递 id。您已将 id 指定为路由模式中的可选参数:

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

因此,如果您不想使用 id,您可以将其他内容作为 key name in the the query component 传递,例如 /Customer/Edit?year=1994

【讨论】:

  • 新记录成功插入到Customer表中。请注意,对于预先添加到表中的记录,编辑、详细信息和删除工作正常。这些不仅适用于新插入的记录。
  • 当我删除 %20 时,记录的链接工作正常。
  • %20 代表空格。调试你的代码并检查为什么这个空间被添加到你的链接中
  • 请查看代码。我已经粘贴了一个截图。您可以轻松检查 ID 中是否有空格。但我没有编辑我的代码。请告诉我在哪里可以编辑?
  • 先生,下载的 Northwind 数据库的客户表中存在问题。默认情况下,该空格会添加到客户 ID 列中。我不知道为什么会这样。但感谢您的帮助。我换了桌子,现在它工作正常。
【解决方案2】:

错误是 404 错误。

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

还在 cmets 中指出,Id 1994 后面有一个编码的空格字符。如果 id 是字符串,您可以将参数更改为键入 string 而不是 int

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

【讨论】:

  • 此代码是从脚手架自动生成的。当我更改此链接时,链接不适用于所有记录,并且在不编辑的情况下,链接仅适用于从创建新过程添加的那些记录。这些链接适用于其余记录。
  • 关注博客,了解使用 ADO.Net 的接口和存储库模式进行 MVC Crud 操作code2night.com/Blog/MyBlog/…
【解决方案3】:

我解决了。我终于换了桌子。 Northwind 数据库的客户表存在问题。我下载数据库备份文件。客户 ID 列正在添加一个空格作为插入值的默认值。

【讨论】:

【解决方案4】:

首先创建模型和 Dbcontext。

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

    }

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

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

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()
    {
    }
}

然后创建控制器,在其中使用存储库中的方法。

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 的操作与您通过 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) |

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

【讨论】:

【解决方案5】:
  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();
            }
        }

【讨论】:

猜你喜欢
相关资源
最近更新 更多
热门标签