1

我有一个需要验证下拉列表的要求。在 Button1 上单击模型应验证未选择下拉菜单,在 Button2 上单击模型应验证下拉菜单已选择为有效值,并且如果该值是来自落下。

我的模型如下:

public class ApprovalInformation
{

    [DisplayName("Approval Decision")]
    public int? ApproveStatusID { get; set; }
    public string ApproveStatus { get; set; }
    public SelectList ApproveStatuses { get; set; }

    [DisplayName("Additional Information")]
    [RequiredIf("ApproveStatus", StringConstants.NotApproved, ErrorMessage = "You must specify the comments if not approved")]
    public string AdditionalInformation { get; set; }
}

目前我有 2 种操作方法,我根据按钮名称的值调用它们。这是控制器代码:

public ActionResult SaveApproval(ApprovalInformation approveInfo,string submit)
    {
        if (submit == "Save For Later")
        {
            Business business = new Business();
            int selectedStatusID = approveInfo.ApproveStatusID??0;
            if ( selectedStatusID!= 0)
            {
                ModelState.AddModelError("ApproveStatusID", "You may not set the Approval Decision before saving a service request for later.  Please reset the Approval Decision to blank");
            }
            if (ModelState.IsValid)
            {
              return RedirectToActionPermanent("EditApproval");
            }

            return View("EditApproval", approveInfo);
        }
        else
        {
            TempData["approverInfo"] = approveInfo;
            return RedirectToActionPermanent("FinishApproval");
        }
    }

我在插入验证时遇到问题,具体取决于单击的按钮。由于在不同的按钮上单击相同的属性应该以两种不同的方式进行验证。如何根据不同的操作在同一模型上在运行时抑制验证或诱导验证。对此的任何想法将不胜感激。

4

1 回答 1

1

我相信这是在您的视图模型上实现IValidatableObject 接口的好情况。ApprovalInformation你可以通过intent to submitor save for laterin the ValidationContextdictionary,以获得你需要的重用。

您也可以在此处放置“如果未设置 ApprovalStatus 则必须设置附加信息”的条件逻辑。

public class ApprovalInformation : IValidatableObject
{
    ... // Properties

    IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
       if (validationContext.ContainsKey("submit"))
       {
          if (ApproveStatusID != 0)
          {
              yield return new ValidationResult("You may not set the Approval Decision before saving a service request for later.  Please reset the Approval Decision to blank", 
                                                 new {"ApproveStatusID"});
          }
       }
    }
}
于 2012-11-23T11:04:14.457 回答