(Model)
public class ShippingAddress
{
[Required(ErrorMessage="请输入姓名")]
[Display(Name="收货人姓名")]
public string Name { get; set; }
[Required(ErrorMessage = "请输入省份")]
[Display(Name = "省份")]
public string Province { get; set; }
[Required(ErrorMessage = "请输入城市")]
[Display(Name = "城市")]
public string City { get; set; }
[Required(ErrorMessage = "请输入行政区")]
[Display(Name = "行政区")]
public string District { get; set; }
[Required(ErrorMessage = "请输入详细地址")]
[Display(Name = "详细地址")]
public string DetailAddress { get; set; }
[Required(ErrorMessage = "请输入邮政编码")]
[Display(Name = "邮政编码")]
public string Zip { get; set; }
[Required(ErrorMessage = "请输入电话号码")]
[Display(Name = "电话号码")]
public string Phone { get; set; }
}
加上
(View)
@using (Html.BeginForm())
{
@Html.ValidationSummary()
foreach (var property in ViewData.ModelMetadata.Properties)
{
<div class="form-group">
<label>@(property.DisplayName ?? property.PropertyName)</label>
@Html.TextBox(property.PropertyName, null, new { @class = "form-control" })
</div>
}
}
等效于
(html)
<form action="/Cart/Checkout" method="post">
<div class="form-group">
<label>收货人姓名</label>
<input class="form-control" data-val="true" data-val-required="请输入姓名" id="Name" name="Name" type="text" value="">
</div>
<div class="form-group">
<label>省份</label>
<input class="form-control" data-val="true" data-val-required="请输入省份" id="Province" name="Province" type="text" value="">
</div>
<div class="form-group">
<label>城市</label>
<input class="form-control" data-val="true" data-val-required="请输入城市" id="City" name="City" type="text" value="">
</div>
<div class="form-group">
<label>行政区</label>
<input class="form-control" data-val="true" data-val-required="请输入行政区" id="District" name="District" type="text" value="">
</div>
<div class="form-group">
<label>详细地址</label>
<input class="form-control" data-val="true" data-val-required="请输入详细地址" id="DetailAddress" name="DetailAddress" type="text" value="">
</div>
<div class="form-group">
<label>邮政编码</label>
<input class="form-control" data-val="true" data-val-required="请输入邮政编码" id="Zip" name="Zip" type="text" value="">
</div>
<div class="form-group">
<label>电话号码</label>
<input class="form-control" data-val="true" data-val-required="请输入电话号码" id="Phone" name="Phone" type="text" value="">
</div>
</form>
- 控制器情况
public ViewResult Checkout()
{
return View(new ShippingAddress());
}
[HttpPost]
public ViewResult Checkout(Cart cart, ShippingAddress shippingDetails)
{
if (cart.lines.Count() == 0)
{
ModelState.AddModelError("", "呃,你的购物车空空如也");
}
if (ModelState.IsValid)
{
orderProcessor.ProcessOrder(cart, shippingDetails);
cart.Clear();
return View("Completed");
}
else
{
return View(shippingDetails);
}
}
}
我们发现,在这个业务处理中,数据流动顺序是View-->Model-->Controller(Checkout)而非严格的数据流动模式(Controller-->Model-->View)。这暴露了MVC的一个致命缺陷,View与Model可以进行双向的数据传递。这看似灵活,实则混乱。