【问题标题】:C# RazorPg - Check if form field is empty and mark as unchangedC# RazorPg - 检查表单字段是否为空并标记为未更改
【发布时间】:2022-12-09 09:05:03
【问题描述】:

I have a form field that allows users to change their email address. If the user doesn't enter anything in the field I want to send "unchanged" to the API. Not blank "" or null.

我想出了这段代码:

if (!String.IsNullOrEmpty(Request.Form["Email"].ToString()))  // Null or blank check
{
 if (Request.Form["Email"].ToString() != user.Email)  // Don't update email if it's the same as the existing one
  {
    user.Email = Request.Form["Email"];
  }
  else
  {
    user.Email = "unchanged";      // I don't want to pass null or blank to the API.
  }
}
else
{
 user.Email = "unchanged";
}

对我来说它看起来很乱。我在页面上有 10 个字段,所以我会在我的控制器中列出 10 次。

有更好的方法吗?

【问题讨论】:

    标签: c# .net-6.0 razor-pages


    【解决方案1】:

    我认为您可以在 User 模型中初始化 Email 属性:

    public string Email { get; set; } = "unchanged"; 
    

    您也可以在默认构造函数中执行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 2020-02-27
      • 1970-01-01
      • 2012-02-21
      相关资源
      最近更新 更多