编辑页面不显示数据

本文关键字:数据 显示 编辑页面 | 更新日期: 2023-09-27 18:11:22

感谢您的帮助!

一切都很顺利,直到我偶然发现了这个:(

当我点击编辑我的显示表,它去编辑值把0在我的id文本字段,但表单的其余部分是空白?

What I have:

 public ActionResult EditProduct(int? id)  
 {
    Product prod = new Product();
    return View(prod); 
 } 

谢谢你们了!

编辑页面不显示数据

在您的代码中,您正在创建一个新产品,然后将其发送到视图,因此它将是空白的,并有一个0作为id。

您需要检索您的产品,然后将其传递给视图。也许像这样:

public ActionResult EditProduct(int? id)  
{
    Product prod = _productRepository.Get(id);// code to retrieve product from database
    if (prod != null)
    {
       return View(prod); 
    }
    else
    {
       return RedirectToAction("Error"); // or whatever...
    }
} 

您需要按id从数据存储中加载产品,而不是创建一个新实例。比如:

return View(db.Products.Find(id))

一个开始学习MVC的好地方是http://www.asp.net/mvc。有很多关于数据驱动mvc网站的教程

创建一个名为IProduct的接口,并带有Get、GetAll、Save等方法。您的存储库类实现(即productrerepository .cs)实现了iproductrerepository,它有一个对ObjectContext的引用(或DbContext正在使用ef 4.1)

有些人更喜欢有一个通用的IRepository接口——但是就像有人对我说的‘通用的存储库是一个童话’

一旦你有了这个,创建

<>之前YourRepository = new repository ();//有些选择传入上下文或通过unity、ninject等注入上下文,这是一个基本的例子。之前

您的存储库有一个方法

<>之前private YourContextName _context = new YourContextName()public Product Get(int productId){返回_context.Products.Where (o => o.ProductId = productId) .Single ();}之前

这就是它的全部。当然还有更高级的实现,但它是相当基本的。

http://blogs.microsoft.co.il/blogs/gilf/archive/2010/01/20/using-repository-pattern-with-entity-framework.aspx

http://www.codeproject.com/KB/database/ImplRepositoryPatternEF.aspx

http://blogs.msdn.com/b/adonet/archive/2009/06/16/using -库-和-单元-工作-模式-与-实体框架- 4 - 0. - aspx