ASPNET MVC3技术要点(8)
发布时间:2021-06-06
发布时间:2021-06-06
ASPNET MVC3技术要点
}
3.1.3 显式调用框架的模型绑定功能
如果视图中无模型变量,需要将模型变量绑定到context。例如: ProductSummary.cshtml视图代码:
@model SportsStore.Domain.Entities.Product
<div class="item">
@if (Model.ImageData != null) {
<div style="float:left;margin-right:20px">
<img width="75" height="75" src="@Url.Action("GetImage", "Product", new { Model.ProductID })" /> </div> }
<h3>@</h3> @Model.Description
@using(Html.BeginForm("AddToCart", "Cart")) { @Html.HiddenFor(x => x.ProductID)
@Html.Hidden("returnUrl", Request.Url.PathAndQuery) <input type="submit" value="+ Add to cart" /> }
<h4>@Model.Price.ToString("c")</h4> </div>
Cart控制器AddToCart动作函数代码:
public RedirectToRouteResult AddToCart(Cart cart, int productId, string returnUrl) {
Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId); if (product != null) {
//GetCart().AddItem(product, 1); cart.AddItem(product, 1); }
return RedirectToAction("Index", new { returnUrl }); }
ProductSummary.cshtml中没有Cart对象,那么AddToCart动作函数的参变量是从哪里来的呢?实际它是在CartModelBinder.cs中实现,代码如下:
public class CartModelBinder : IModelBinder {
private const string sessionKey = "Cart";
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
// get the Cart from the session
Cart cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
上一篇:S3C44B0 学习板使用指南
下一篇:朗文交互英语第二级A2答案