我们在插入一条数据的时候会验证数据的有效性.
2.0中提供了验证指定的model
我们的实例代码如下
controller:
public ActionResult Index()
{
return View();
}
看起来这是一个空的ActionResult我们add view
当然 这里我们会使用默认插入模版.
view代码
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.User_name) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.User_name) %>
<%= Html.ValidationMessageFor(model => model.User_name) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.User_pass) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.User_pass) %>
<%= Html.ValidationMessageFor(model => model.User_pass) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.User_type) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.User_type) %>
<%= Html.ValidationMessageFor(model => model.User_type) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.User_Info) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.User_Info) %>
<%= Html.ValidationMessageFor(model => model.User_Info) %>
</div>
<input type="text" id="text" name="text" />
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
这样 我们的添加页面就ok了
再看处理代码
TryValidateModel(admin);
if (string.IsNullOrEmpty(admin.User_name))
ModelState.AddModelError("User_name", "用户名不能为空");
if (ModelState.IsValid)
{
return RedirectToAction("About");
}
return View();
这里我简单的验证用户名是否输入为空
运行结果如下
很简单的一个验证 您可以去完善这个验证.