手机版

ASPNET MVC3技术要点(8)

时间:2025-07-07   来源:未知    
字号:

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];

ASPNET MVC3技术要点(8).doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
×
二维码
× 游客快捷下载通道(下载后可以自由复制和排版)
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
注:下载文档有可能出现无法下载或内容有问题,请联系客服协助您处理。
× 常见问题(客服时间:周一到周五 9:30-18:00)