验证来自数据库的int数据

时间:2016-08-24 19:56:12

标签: c# validation asp.net-mvc-4

以下代码说明了类模型的使用:Student

public class Student: IAbstract
{
    public int StudentID { get; set; }
    public string FirstName { get; set; }
    public int Age { get; set; }
    //Some methods
}

这是来自index()

的方法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);
}

正如你所看到的,我必须检查“年龄”是否为空,因为在我的数据库中(出于测试目的),一些学生没有年龄设置。但是我不想为视图设置Age0,这是在视图中显示“void”单元格而不是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>

1 个答案:

答案 0 :(得分:2)

Age设置为可以为空的int:

public int? Age { get; set; }

然后默认值为空,不为0.

您的解析逻辑可能如下所示:

Age = item.IsNull("Age") ? null : (int?)Convert.ToInt32(item["Age"]) //Here