简体   繁体   English

mvc模型绑定和null检查

[英]mvc model binding and null checking

I have a simple model as below 我有一个简单的模型如下

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

On my razor view i have two textboxes thats mapping to these two properties. 在我的剃刀视图上,我有两个映射到这两个属性的文本框。 Only one of the text box is a required field and other one can be left empty.(that is either property1 or property2 can be entered or both can be entered..however both cannot be left blank) 只有一个文本框是必填字段,另一个可以保留为空。(即可以输入property1或property2,也可以同时输入两者。但是不能将两者都保留为空白)

My controller action method is quite simple 我的控制器动作方法很简单

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

If i do this on my attribute of my model, the above statement works..why is null alone failing ? 如果我在模型的属性上执行此操作,则以上语句起作用。.为什么null单独失败?

 [DisplayFormat(ConvertEmptyStringToNull = false)]

What i dont understand is why is the string.IsNullOrEmpty fails? 我不明白的是为什么string.IsNullOrEmpty失败?

Here is the view.. 这是视图。

     <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>

Thanks for your thoughts... 感谢您的想法...

With this code, I guess that you'll never reach the string.IsNullOrEmpty code. 使用此代码,我想您永远不会到达string.IsNullOrEmpty代码。 But you have to show us the view to solve the real problem. 但是您必须向我们展示解决实际问题的观点。

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

-- EDIT -- To perform complex validation logic, implement IValidatableObject on your ViewModel: -编辑-要执行复杂的验证逻辑, IValidatableObject在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"}
              );
         }
     }
}

Check the ModelState in your controller action: 在控制器操作中检查ModelState:

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

You can check like this: 你可以这样检查:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM