【问题标题】:display a message to user if field is blank如果字段为空,则向用户显示消息
【发布时间】: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. 参数 1:无法从 'int?' 转换到“字符串”

  2. 当前上下文中不存在名称“MessageBox” 3) 'string.IsNullOrEmpty(string)' 的最佳重载方法匹配有 一些无效参数

  3. '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");         

消息框和出生日期归档的以下问题相同。

  1. 运算符“==”不能应用于“System.DateTime”类型的操作数?和'int'

我是 c# 新手,但我认为我的思路有点正确,我认为只需要一点帮助或任何建议。

问候 贝蒂

【问题讨论】:

  • MessageBox 是窗口形式(在网络应用程序中没有用)。添加ModelState 错误并返回视图,以便消息显示在您的@Html.ValidationSummary() - ModelState.AddModelError("", "your error message");返回视图(模型);`
  • 并使您的属性可以为空 - int? AgeNotKnownDateTime? 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


【解决方案1】:

? 表示nullable,其默认值为null,如果我使用int?,其默认值为null,如果我使用int,其默认值为0

关于验证,您可以在MVC 中使用ModelState 进行验证并添加自定义验证

    @Html.ValidationMessage("validation")
    @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control", @placeholder = "dd-mm-yyyy" } })
    @Html.EditorFor(model => model.AgeNotKnown, new { htmlAttributes = new { @class = "form-control", @placeholder = "Age in Years" } })

我使用了@Html.ValidationMessage("validation"),如果我返回任何验证消息并在您的action 中显示验证消息

 if (cls.DateOfBirth == null && cls.AgeNotKnown == null)
            {
                ModelState.AddModelError("validation","Please select one");
                return View();
            }

实际上,如果两者都是null,它将检查条件,然后它将返回到同一视图,包括在视图中定义的key validation 的验证消息。

【讨论】:

    【解决方案2】:

    首先MessageBox类属于windows窗体。如果你想 wanr 用户,你应该使用验证。我更喜欢jquery validation

    要像这样添加控件,只需在代码中放置一个断点,然后查看表单中的数据即可。这样您就可以决定如何控制您的数据。

    System.DateTime?而int?,这个问号告诉你这些变量可以为null。所以你应该在比较时考虑到这一点。

    【讨论】:

      【解决方案3】:

      首先为这种验证创建 ViewModel

      public class ClientViewModel
      {
          [Required, DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
          public DateTime Date { get; set; }
      
          [Required]
          public int Age { get; set; }
      }
      

      在视图中

      @model  Models.ClientViewModel @*reference to your model usally create in Models folder*@
      
      @Html.ValidationSummary() @* add this for validation summary displays here.*@
      
      @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control", @placeholder = "dd-mm-yyyy" } })
      @Html.ValidationMessageFor(m => m.Date)
      
      @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control", @placeholder = "Age in Years" } })
      @Html.ValidationMessageFor(m => m.Age)
      
      @* Add jqueryval bundles which is created in app_start/BundleConfig  *@
      @section Scripts{
          @Scripts.Render("~/bundles/jqueryval")
          }
      

      在控制器中

      //Change the name of PostMethod 
      public ActionResult PostMethod(Models.ClientViewModel model )
      {
          if (ModelState.IsValid)
          {
              // do your stuff
          }
      
      
          return View();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-22
        • 1970-01-01
        • 2015-12-20
        • 2014-11-10
        相关资源
        最近更新 更多