C# mvc模型绑定和空检查

C# mvc模型绑定和空检查,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我有一个简单的模型如下 public class TestModel { public string property1 {get;set;} public string property2 {get;set;} } 在我的razor视图中,有两个文本框映射到这两个属性。 只有一个文本框是必填字段,另一个文本框可以为空。(即可以输入property1或property2,也可以同时输入两者。。但不能同时为空) 我的控制器动作方法很简单 public ActionRes

我有一个简单的模型如下

public class TestModel
{
    public string property1 {get;set;}
    public string property2 {get;set;}
}
在我的razor视图中,有两个文本框映射到这两个属性。 只有一个文本框是必填字段,另一个文本框可以为空。(即可以输入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>

@LabelFor(m=>m.property1,新的{@class=“col-sm-3控制标签”})
@TextBoxFor(m=>m.property1,新的{@class=“form control”})
@LabelFor(m=>m.property2,新的{@class=“col-sm-3控制标签”})
@TextBoxFor(m=>m.property2,新的{@class=“form control”})

谢谢你的想法…

有了这段代码,我想你永远都不会找到string.IsNullOrEmpty代码。但你必须向我们展示解决真正问题的观点

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

有了这段代码,我想您永远也不会找到string.IsNullOrEmpty代码。但你必须向我们展示解决真正问题的观点

    public ActionResult MyMethod(TestModel tmodel)
    {
       if(tmodel != null)
       {
          if (!string.IsNullOrEmpty(tmodel.property1))
          {
          }
       }              
   }
--编辑-- 要执行复杂的验证逻辑,请在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"}
              );
         }
     }
}
--编辑-- 要执行复杂的验证逻辑,请在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"}
              );
         }
     }
}

您可以这样检查:

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);
            }
        }

您可以这样检查:

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);
            }
        }


您可以显示视图吗?IsNullOrEmpty失败,因为您正在检查tmodel.property1是否为null,但它是tmodel that null失败的原因是什么?如果块中的代码在不应该执行时被执行,是否会出现错误?您是否得到一个NullReferenceException,在这种情况下失败的不是IsNullOrEmpty?我想它会抛出一个异常
//代码在这个空检查中失败..对象引用未设置为对象的实例
。这是因为模型本身为空。当只有一个属性为空时会发生这种情况吗?在isnullorempty检查之前,如果我这样做,如果(tmodel!=null),那么就通过了..所以是string.isnullorempty失败了..您能显示视图吗?isnullorempty失败是因为您正在检查tmodel.property1是否为null,但这是tmodel失败了吗?如果块中的代码在不应该执行时被执行,是否会出现错误?您是否得到一个NullReferenceException,在这种情况下失败的不是IsNullOrEmpty?我想它会抛出一个异常
//代码在这个空检查中失败..对象引用未设置为对象的实例
。这是因为模型本身为空。只有一个属性为空时会发生这种情况吗?在isnullorempty检查之前,如果我这样做,如果(tmodel!=null),那么就通过了..所以是string.isnullorempty失败了..我用视图更新了我的代码..还有..当我做了你做的精确检查时,它通过了第一次检查,在我的例子中,tmodel不是空的,我已经用视图更新了我的代码…还有..当我做了你做的精确检查时,它通过了第一次检查,因为在我的例子中tmodel不是空的,我相信他不想要所需的属性1,也不想要属性2。只是两者不能都是空的。是的,我不能像你提到的那样做必需的操作,因为任何一个字段都可以是空的…请查看我的编辑,它显示了如何处理复杂的验证逻辑。Georg我不是在寻找验证逻辑。我的问题是为什么string.isnullorempty调用失败?好的,我认为这可以解决你的根本问题(检查两个输入中是否有一个为空)以标准方式。你检查了POST数据吗?我猜你的字符串不是以null或字符串的形式发送的。空。我相信他不需要属性1作为必需的,也不需要属性2。只是两者不能都是空的。是的,我不能像你提到的那样做必需的,因为两个字段都可以是空的…请查看我的编辑,它显示了如何处理复杂的验证逻辑。Georgeg我不是在寻找验证逻辑..我的问题是为什么string.isnullorempty调用失败?好的,我认为这将以标准方式解决您的根本问题(检查两个输入中是否有一个是空的)。您是否检查了POST数据?我想您的字符串不是以null或string.empty的形式发送的。