微软网络应用架构相关...
想知道我没有为我的新 Web 应用程序使用 .Net 的 MVC 是否犯了一个错误?我开始在 ASP Classic 中进行 Web 开发,并随着 ASP.net 的每次迭代而前进。在过去的几个月里,我一直在玩弄 ASP.net MVC,只是不喜欢它的某些部分。我喜欢路由、剃刀和查看特定模型的想法。但是,在添加了一些功能之后,我的应用程序似乎变得过于复杂——当我查看 nopCommerce 和 Umbraco 等应用程序的 MVC 版本与之前的版本相比时,我觉得也是如此。
我回去基本上开始编写一个 .Net 网站/MVC 混合体。我为实现数据注释验证的“视图模型”创建了自己的基类;一个简单的映射器,用于将表单提交绑定到模型并将实体属性映射到模型属性,反之亦然;为分页、检查、选择和偶数/奇数等内容创建了扩展方法和助手;runat="server"
使用不需要视图状态的重复器、文字和标准 HTML 标记等控件。
这种方法似乎让我可以两全其美,让我的“控制器”代码接近“视图”,并且一切都在中等信任下工作。
这是一些示例代码:
public partial class Admin_Users_RoleAdd : System.Web.UI.Page
{
protected class RoleAddModel : BaseModel
{
[Required, StringLength(100)]
public string Name { get; set; }
[StringLength(250)]
public string Description { get; set; }
public override bool Validate()
{
if (base.Validate() && Cortex.DB.Roles.Any(r => r.Name == Name))
Errors["Name"] = "Already in use";
return Errors.Count == 0;
}
}
protected RoleAddModel model = new RoleAddModel();
protected override void OnInit(EventArgs e)
{
if (Request.Form["Submit"].HasValue())
{
SimpleMapper.FormMap<RoleAddModel>(model);
if (model.Validate())
{
var entity = new Role();
SimpleMapper.Map<RoleAddModel, Role>(model, entity);
Cortex.DB.Roles.AddObject(entity);
Cortex.DB.SaveChanges();
Response.Redirect("Roles.aspx");
}
}
base.OnInit(e);
}
}
和“视图”:
<h1>Add Role</h1>
<div id="MainForm" class="form">
<%= model.GetErrorMessage("Error") %>
<form action="<%= Request.RawUrl %>" method="post">
<div class="formField">
<label for="Name">Name</label> <%= model.GetErrorMessage("Name") %><br />
<input type="text" name="Name" value="<%: model.Name %>" class="required" maxlength="100" />
</div>
<div class="formField">
<label for="Description">Description</label> <%= model.GetErrorMessage("Description") %><br />
<textarea rows="8" cols="40" name="Description" maxlength="250"><%: model.Description %></textarea>
</div>
<div class="buttons">
<input type="submit" name="Submit" value="Create" class="primary" />
<a href="Roles.aspx">Back</a>
</div>
</form>
</div>
以后我会对这种方法感到遗憾吗?目前我能想到的主要是测试能力,但 VWD Express 无论如何都不支持它。