ASP.NET MVC SportStore 购物网示例(7)

为实体类Product添加验证消息

[Table(Name="Products")]

public class Product : IDataErrorInfo

{

[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]

public int ProductID { get; set; }

[Column]

public string Name { get; set; }

[Column]

public string Description { get; set; }

[Column]

public decimal Price { get; set; }

[Column]

public string Category { get; set; }

public string this[string propName]

{

get

{

if ((propName == "Name") && string.IsNullOrEmpty(Name))

return "Please enter a product name";

if ((propName == "Description") && string.IsNullOrEmpty(Description))

return "Please enter a description";

if ((propName == "Price") && (Price < 0))

return "Price must not be negative";

if ((propName == "Category") && string.IsNullOrEmpty(Category))

return "Please specify a category";

return null;

}

}

public string Error { get { return null; } } // Not required

}

为了使更新到数据库的数据确实有效,在SaveProduct方法中添加EnsureValid()方法。

private void EnsureValid(IDataErrorInfo validatable, params string[] properties)

{

if (properties.Any(x => validatable[x] != null))

throw new InvalidOperationException("The Object is invalid");

}

public void SaveProduct(Product product)

{

EnsureValid(product, "Name", "Description", "Category", "Price");

.....

}

添加新的产品

添加一个新的产品很容易实现,我们只需要提交一个空的Product对象到edit视图就可以了。

public ViewResult Create()

{

return View("Edit",new Product());

}

将把单击Save进默认的Action会提供到Create Action 所以,修改Form的提供位置。

修改 Edit.aspx :

<% using (Html.BeginForm("Edit","Admin")) {%>

删除一个产品

添加一个测试

[Test]

public void Delete_Action_Deletes_Product_Then_Redirects_To_Index()

{

// Arrange

AdminController controller = new AdminController(mockRepos.Object);

Product prod24 = mockRepos.Object.Products.First(p => p.ProductID == 24);

// Act (attempt to delete product 24)

RedirectToRouteResult result = controller.Delete(24);

// Assert

Assert.AreEqual("Index", result.RouteValues["action"]);

Assert.AreEqual("Product 24 has been deleted",

controller.TempData["message"]);

mockRepos.Verify(x => x.DeleteProduct(prod24));

}

添加删除接口

public interface IProductsRepository

{

IQueryable<Product> Products { get; }

void SaveProduct(Product product);

void DeleteProduct(Product product);

}

在SqlRepositoryProduct添加方法

public void DeleteProduct(Product product)

{

productsTable.DeleteOnSubmit(product);

productsTable.Context.SubmitChanges();

}

添加视图方法:

public RedirectToRouteResult Delete(int id)

{

Product product = (from p in productsRepository.Products

where p.ProductID == id

select p).First();

productsRepository.DeleteProduct(product);

TempData["message"] = product.Name + " has been deleted";

return RedirectToAction("Index");

}

管理员安全管理

打开web.config文件,更新authentication

<authentication mode="Forms">

<!--<forms loginUrl="~/Account/LogOn" timeout="2880"/>-->

<forms loginUrl="~/Account/LogOn" timeout="2880">

<credentials passwordFormat="SHA1">

<user name="admin" password="e9fe51f94eadabf54dbf2fbbd57188b9abee436e" />

</credentials>

</forms>

</authentication>

用户名是admin密码是 mysecret

为 AdminController类添认证标记

[Authorize]

public class AdminController : Controller

添加AccountController类:

public class AccountController : Controller

{

[AcceptVerbs(HttpVerbs.Get)]

public ViewResult LogOn()

{

return View();

}

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult LogOn(string name, string password, string returnUrl)

{

if (FormsAuthentication.Authenticate(name, password))

{

// Assign a default redirection destination if not set

returnUrl = returnUrl ?? Url.Action("Index", "Admin");

// Grant cookie and redirect

FormsAuthentication.SetAuthCookie(name, false);

return Redirect(returnUrl); ;

}

else

{

ViewData["lastLoginFailed"] = true;

return View();

}

}

}

为LogOn添加视图:

clip_image001

图像上传

修改领域模型和数据库

为Product类添加属性:

[Column]

public byte[] ImageData { get; set; }

[Column]

public string ImageMimeType { get; set; }

为数据库添加字段:

clip_image002

为Edit.aspx添加上传:

<p>

Image:

<% if (Model.ImageData == null)

{ %>

None

<% }

else

{ %>

<img src="<%= Url.Action("GetImage", "Products",new { Model.ProductID }) %>" />

<% } %>

<div>

Upload new image:

<input type="file" name="Image" /></div>

</p>

<input type="submit" value="Save" />

修改Form

<% using (Html.BeginForm("Edit", "Admin", FormMethod.Post,

new { enctype = "multipart/form-data" })) { %>

保存图片到数据库

修改Edit方法:

[HttpPost]

public ActionResult Edit(Product product,HttpPostedFileBase image)

{

//try

//{

// TODO: Add update logic here

if (ModelState.IsValid)

{

if (image != null)

{

product.ImageMimeType = image.ContentType;

product.ImageData = new byte[image.ContentLength];

image.InputStream.Read(product.ImageData, 0, image.ContentLength);

}

显示图片

为ProductsController添加方法:

public FileContentResult GetImage(int ProductID)

{

Product product = (from p in productsRepository.Products

where p.ProductID == ProductID

select p).First();

return File(product.ImageData, product.ImageMimeType);

}

更新ProductSummary.ascxj显示图片

<% if (Model.ImageData != null)

{ %>

<div style="float: left; margin-right: 20px">

<img src="<%= Url.Action("GetImage", "Products",

new { Model.ProductID }) %>" />

</div>

<% } %>

<h3>

<%=Model.Name %></h3>

F5运行.

clip_image004

全部结束!祝好运!

转载请注明出处! Author: im@xingquan.org

posted @ 2011-03-24 21:10  敏捷学院  阅读(453)  评论(2编辑  收藏  举报