从数据库
问题描述:
验证int数据下面的代码说明了使用类模型:从StudentController
从数据库
public ActionResult Index()
{
var model = new List<Student>();
var objStudent = new Student();
var cmd = new SqlBuilder();
cmd.CommandText = "SELECT StudentID, FirstName, Age FROM Students";
var data = objStudent.Select(cmd);
foreach (DataRow item in data.Tables[0].Rows)
{
model.Add(new Student
{
StudentID = Convert.ToInt32(item["StudentID"]),
FirstName = item["FirstName"].ToString(),
Age = item.IsNull("Age")?0:Convert.ToInt32(item["Age"]) //Here
});
}
return View("Index", model);
}
Student
public class Student: IAbstract
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public int Age { get; set; }
//Some methods
}
这种方法index()
正如你可以看到我有检查“年龄“为空,因为在我的数据库(用于测试目的),一些学生没有设定年龄。但我不想为视图设置Age
到0
,所以这是在视图中显示“空白”单元而不是0
?的最佳方式。视图代码的
部分:
<body>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentID)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.StudentID)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.StudentID }) |
@Html.ActionLink("Details", "Details", new { id = item.StudentID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.StudentID })
</td>
</tr>
}
</table>
</body>
答
设置Age
是一个可空INT:
public int? Age { get; set; }
,那么默认值是什么,不是0
你的分析逻辑然后可以看起来像:
Age = item.IsNull("Age") ? null : (int?)Convert.ToInt32(item["Age"]) //Here
我想过了,但我得到以下错误:错误条件表达式的类型无法确定,因为''和'int'' –
FacundoGFlores
之间没有隐式转换,是的,你需要将右转手边到'int?',使条件操作有效。看我的编辑。 – Jonesopolis