Learning asp.net mvc 3 + EF with code code. I am new to both. My example is trivial, but I still can't get it to work. Something simple and obvious is missing ...
I have a class:
public class Product
{
[HiddenInput(DisplayValue = false)]
public int ProductID { get; set; }
[Required(ErrorMessage = "Please enter a product name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a description")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Required]
[Range(0.01, double.MaxValue, ErrorMessage = "Please enter a positive price")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Please specify a category")]
public string Category { get; set; }
}
and a DbContext:
public class EFDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
and repository:
public class EFProductRepository : IProductRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products
{
get
{
return context.Products;
}
}
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
context.Products.Add(product);
context.SaveChanges();
}
}
Mvc controller:
public class AdminController : Controller
{
private IProductRepository repository;
public AdminController(IProductRepository repo)
{
repository = repo;
}
public ViewResult Index()
{
return View(repository.Products);
}
public ViewResult Edit(int productId)
{
Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId);
return View(product);
}
[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
repository.SaveProduct(product);
TempData["message"] = string.Format("{0} has been saved", product.Name);
return RedirectToAction("Index");
}
else
{
return View(product);
}
}
}
Allows me to view the list of products, open the edit view, check everything according to the set of attributes ...
When I save the checked changes, it goes to the Http Post method Editand does the necessary SaveChanges().
It does not throw any exceptions, it continues and redirects me to the list of products.
The changed item remains unchanged.
The underlying database (connected via connectionstringsin web.config) remains unchanged.