MVC将用户提交的数据传递到Action的参数,也就是ModelBinder 使用Post数据更新Teacher对象,类似与DataSet里面的数据绑定,但这里称之为模型绑定,在更新对象的同时,设置ModelState(ModelState封装了Model的状态),其属性IsVaild表示Model是否更新成功,倘若服务器端验证失败,Model将不更新,ModelState则保存了验证失败的原因。但服务器端到底是用什么来执行验证呢?相信很多学者都很期待这个答案,那就是DataAnnotations,ASP.NET MVC中是使用它来进行验证的。验证就是Action的操作,其参数可以是对象也可以是元参数类型的参数。当参数是对象时,ModelBinder通过检索对象的所有属性,逐一对比,匹配成功时如果值为空,则分配给属性为空值,如果无法执行空值分配,会设置为缺省值同时设置IsValid为false;如果是元参数类型,匹配时候分配值,不成功则设置为缺省值,对于字符串为Null,整型为0。
1、修改Teacher类装饰属性。
public class Teacher
{
[Key]//作用是将Id设置为Teacher的主键
public int TeacherId { get; set; }
[StringLength(5,ErrorMessage="Name length should not be greater than 5")]
public string TeacherName { get; set; }
[Required(ErrorMessage = "Enter teacher Age")]
public int TeacherAge { get; set; }
}
2、修改CreateTeacher.cshtml的form内容
<form action ="/Teacher/SaveTeacher" method="post">
<table >
<tr>
<td>
Teacher Name:
</td>
<td>
<input type="text" name="TeacherName" id="TxtName"value="" />
</td>
</tr>
<tr>
<td colspan="2" align="right" >@Html.ValidationMessage("TeacherName")
</td>
</tr>
<tr>
<td>
Teacher Id:
</td>
<td >
<input type="text" name ="TeacherId" id="TxtId" value=""/>
</td>
</tr>
<tr>
<td>
Teacher Age:
</td>
<td>
<input type="text" name="TeacherAge" id="TxtAge"value="" />
</td>
</tr>
<tr>
<td colspan="2" align="right">@Html.ValidationMessage("TeacherAge")
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="BtnSubmit" value="Save"/>
<input type="button" name ="BtnReset" value="Reset" οnclick="ResetForm()" />
<input type="submit" name="BtnSubmit" value="Cancel "/>
</td>
</tr>
</table>
</form>
3、修改Action SaveTeacher的方法
public ActionResult SaveTeacher(Teacher t, string BtnSubmit)
{
switch(BtnSubmit)
{
case "Save":
if (ModelState.IsValid)
{
TeacherBusinessLayer tBusinessLayer = new TeacherBusinessLayer();
tBusinessLayer.SaveTeacher(t);
return RedirectToAction("Index");
}
else
{
return View("CreateTeacher");
}
case "Cancel ":
return RedirectToAction("Index");
}
return new EmptyResult();
}
4、运行测试,但出现报错问题“The model backing the 'SalesERPDAL' context has changed since the database was created. Consider using Code First Migrations to update the database.”
解决方法:在Global.asax.cs的Application_Start()最后加入
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SchoolERPDAL>());
A | explain:
1、@Html.ValidationMessage解释:
@是Razor代码,Html是HtmlHelper类的实例,而ValidationMessage是HtmlHelper类的函数,用来显示错误信息。类似于throw new Expection这样的意思,也许我的解释有错,大概就是这个意思吧。
2、ModelBinder更新ModelState,ValidationMessage根据关键字显示错误信息,即在对于TeacherName时,错误信息即为Teacher类[StringLength(5,ErrorMessage="Name length should not be greater than 5")]的信息。
3、如果有个新的Teacher English属性,但它可以为空则在Teacher中
Public string? EnglishName{get;set;}
转载请标明出处http://blog.youkuaiyun.com/jasonhds/版权所有,翻版必究~谢谢合作!