【问题标题】:mvc model binding and null checkingmvc 模型绑定和空值检查
【发布时间】:2016-03-09 14:13:10
【问题描述】:

我有一个简单的模型如下

public class TestModel
{
    public string property1 {get;set;}
    public string property2 {get;set;}
}

在我的剃刀视图上,我有两个文本框,它们映射到这两个属性。 文本框只有一个是必填字段,另一个可以留空。(即property1或property2可以输入,或者两者都可以输入。但是两者都不能留空)

我的控制器动作方法很简单

     public ActionResult MyMethod(TestModel tmodel)
     {
          //code fails on this null check..object reference not set to instance of object 
          if (!string.IsNullOrEmpty(tmodel.property1))
          {
          }
      }

如果我对模型的属性执行此操作,则上述语句有效..为什么 null 单独失败?

 [DisplayFormat(ConvertEmptyStringToNull = false)]

我不明白为什么 string.IsNullOrEmpty 会失败?

这是视图..

     <div class="form-group">
        @Html.LabelFor(m => m.property1, new { @class = "col-sm-3 control-label" })
        <div class="col-sm-4">
            @Html.TextBoxFor(m => m.property1, new { @class = "form-control"})
        </div>          
    </div>

    <div class="form-group">
         @Html.LabelFor(m => m.property2, new { @class = "col-sm-3 control-label" })
         <div class="col-sm-4">
        @Html.TextBoxFor(m => m.property2, new { @class = "form-control" })
    </div>

感谢您的意见...

【问题讨论】:

  • 你能展示一下视图吗?
  • IsNullOrEmpty 失败,因为您正在检查 tmodel.property1 是否为 null,但它是 tmodel 那是 null
  • 失败怎么办?您是否收到错误,if 块内的代码在不应该执行时被执行?您是否收到 NullReferenceException,在这种情况下不是 IsNullOrEmpty 失败?
  • 我认为它会引发异常//code fails on this null check..object reference not set to instance of object。发生这种情况是因为模型本身为空。当只有一个属性为空时会发生这种情况吗?
  • 在 isnullorempty 检查我是否这样做之前,如果(tmodel!=null),那么它通过了..所以它的 string.isnullorempty 失败了......

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


【解决方案1】:

使用这段代码,我猜你永远不会到达 string.IsNullOrEmpty 代码。但是你必须向我们展示解决真正问题的观点。

    public ActionResult MyMethod(TestModel tmodel)
    {
       if(tmodel != null)
       {
          if (!string.IsNullOrEmpty(tmodel.property1))
          {
          }
       }              
   }

【讨论】:

  • 我已经用视图更新了我的代码......另外......当我做了你所做的确切检查时,它通过了第一次检查,因为在我的情况下 tmodel 不为空
【解决方案2】:

-- 编辑-- 要执行复杂的验证逻辑,请在您的 ViewModel 上实现 IValidatableObject

public class TestModel : IValidatableObject {

    public string property1 {get;set;}
    public string property2 {get;set;}

     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
         if (string.IsNullOrWhiteSpace(property1) && string.IsNullOrWhiteSpace(property2)) {
              yield return new ValidationResult(
                  "some error message", 
                  new[] { "property1", "property2"}
              );
         }
     }
}

检查控制器操作中的 ModelState:

public ActionResult MyMethod(TestModel tmodel) {
   if(!ModelState.IsValid) {
      // error handling here
   }              
}

【讨论】:

  • 我相信他不想要property1,也不想要property2。只是两者都不能为空。
  • 是的,我不能像你提到的那样做所需的,因为任何一个字段都可以为空......
  • 请看我的编辑,它展示了如何处理复杂的验证逻辑。
  • Georg 我不是在寻找验证逻辑。我的问题是为什么 string.isnullorempty 调用失败?
  • 好的,我认为这会以标准方式解决您的潜在问题(检查两个输入中的一个是否为空)。您检查过 POST 数据吗?猜猜你的字符串不是作为 null 或 string.Empty 发送的。
【解决方案3】:

你可以这样检查:

public ActionResult MyMethod(TestModel tmodel)
        {
            if (string.IsNullOrEmpty(tmodel.property1) && string.IsNullOrEmpty(tmodel.property2))
            {
                ModelState.AddModelError("property1", "The field property1 can only be empty if property2 is not");
                ModelState.AddModelError("property2", "The field property2 can only be empty if property1 is not");
            }

            if (ModelState.IsValid)
            {
                return RedirectToAction("otherAction");   //or do whatever you want            
            }
            else
            {
                //back to form with the errors highlighted
                return View(tmodel);
            }
        }

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多