【发布时间】:2017-03-02 20:06:21
【问题描述】:
下午的人们,
我是 C# 的新手,我试图创建一个 if 语句来检查两个字段的值,如果这两个字段都是空白的,然后向用户显示一条消息。
我的两个字段是 DateofBirth,数据类型为 DateTime,Age 数据类型为 int。我使用的是 studio 2013 并且有一个 c# mvc 项目。
在我的 create.cshtml 页面中,我对这两个表单字段使用了 razor 语法。
@Html.EditorFor(model => model.client.DateOfBirth, new { htmlAttributes = new { @class = "form-control", @placeholder = "dd-mm-yyyy" } })
和
@Html.EditorFor(model => model.client.AgeNotKnown, new { htmlAttributes = new { @class = "form-control", @placeholder = "Age in Years" } })
用户在提交表单时需要填写一个或另一个字段。
在我的控制器和我的 HttpPost 中为 ActionResult 创建。我已经尝试了几种方法来通过 if 语句使其工作,但我似乎得到了这个工作。
我尝试过使用 string.IsNullOrEmpty 方法,但由于这些是 DateTime 和 int 数据类型,这将不起作用。请参阅下面的示例。
if (string.IsNullOrEmpty(clientViewRecord.client.AgeNotKnown));
{
MessageBox.Show("please an Age if DOB not known");
}
db.ClientRecords.Add(clientViewRecord.client);
db.SaveChanges();
return RedirectToAction("MainMenu", "Home");
我在这里遇到三个错误:
参数 1:无法从 'int?' 转换到“字符串”
当前上下文中不存在名称“MessageBox” 3) 'string.IsNullOrEmpty(string)' 的最佳重载方法匹配有 一些无效参数
'string.IsNullOrEmpty(string)' 的最佳重载方法匹配有 一些无效参数
我试图让这个工作的另一种方法是以下......
if (clientViewRecord.client.AgeNotKnown == 0 || clientViewRecord.client.DateOfBirth == 0);
{
MessageBox.Show("please enter an Age or if DOB");
}
db.ClientRecords.Add(clientViewRecord.client);
db.SaveChanges();
return RedirectToAction("MainMenu", "Home");
消息框和出生日期归档的以下问题相同。
- 运算符“==”不能应用于“System.DateTime”类型的操作数?和'int'
我是 c# 新手,但我认为我的思路有点正确,我认为只需要一点帮助或任何建议。
问候 贝蒂
【问题讨论】:
-
MessageBox是窗口形式(在网络应用程序中没有用)。添加ModelState错误并返回视图,以便消息显示在您的@Html.ValidationSummary()- ModelState.AddModelError("", "your error message");返回视图(模型);` -
并使您的属性可以为空 -
int? AgeNotKnown和DateTime? DateOfBirth以便您使用if (DateOfBirth.HasValue)测试它们 -
但是处理这个用户界面的正确方法是创建一个实现
IClientValidatable的自定义验证属性,这样您就可以获得客户端和服务器端验证 - The Complete Guide To Validation In ASP.NET MVC 3 - Part 2 -
@StephenMuecke 非常感谢,我的两个字段在我的模型中都可以为空。公共 Nullable
AgeNotKnown { get;放; }, public Nullable DateOfBirth { get;放; }。我会看一下您在消息中引用的指南。
标签: c# asp.net-mvc asp.net-mvc-4 razor