2014-03-01 2 views
0

저는 ASP.NET MVC를 처음 사용하고 초보자 용 질문에 부딪 혔습니다.ASP.NET MVC 5, Entity Framework, 모델 데이터 제외

이 나는 ​​몇 가지 조건이 충족되는 경우 일부 데이터 만 컨트롤에 뷰에서 보내야 양식을 만들었습니다. 예를 들어, 클릭하지 않은 텍스트 필드가 사용자가 이전 날짜를 입력 할 수있는 곳에 나타나야하는 경우 "오늘"이라는 텍스트가있는 확인란이 있습니다.

내 질문은 : 어떻게해야합니까 (나는 이미 자바 스크립트로 해결했습니다, 필드를 작성/지우기,하지만 그건 정말 못생긴) 일부 조건에 따라 필드를 제외/포함하도록 말해.

나는이 같은 시도 :

public ActionResult Create([Bind(Include = "EventID,ActivityID", Exclude = "EventDate")] FSEvent fsevent) 
{ 
     if (ModelState.IsValid) 
     { 
      if (fsevent.EventDate == DateTime.MinValue) 
      { 
       fsevent.EventDate = DateTime.Now; 
      } 

      db.FSEvents.Add(fsevent); 
      db.SaveChanges(); 

      return RedirectToAction(returnUrl); 
     } 

     ViewBag.ActivityID = new SelectList(db.FSEventItems, "ActivityID", "Name", fsevent.ActivityID); 
     ViewBag.UserID = new SelectList(db.FSUsers, "UserID", "FirstName", fsevent.UserID); 

     return View(fsevent); 
    } 

을하지만 브라우저 나 (사용자) 자바 스크립트 검증 (에서 MVC EF의 BUIT으로는 "EVENTDATE 필드가 필요합니다"오류 메시지를 제공합니다 그래서 자바 스크립트를 사용하지 않으면 그것은 잘 작동합니다).

답변

1


비슷한 문제가 발생하여 사용자 지정 속성을 사용하여 해결했습니다.
ViewModel, View 및 Attribute는 아래에서 확인할 수 있습니다.

뷰 모델

public class TheViewModel{ 

    [Display(Name = "YourOtherFieldDisplayName", ResourceType = typeof(YourResourceFile))] 
    public string YourOtherField { get; set; } 

    [Display(Name = "YourFieldDisplayName", ResourceType = typeof(YourResourceFile))] 
    [RequiredIf("TheOtherField", true, ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(YourResourceFile))] 
    public string YourField { get; set; } 
} 

보기

@Html.LabelFor(model => model.YourOtherField) 
@Html.CheckBoxFor(model => model.YourOtherField) 
@Html.LabelFor(model => model.YourField) 
@Html.TextBoxFor(model => model.YourField) 
@Html.ValidationMessageFor(model => model.YourField) 

namespace YOURNAMESPACE.attributes 
{ 
    public class RequiredIfAttribute : ValidationAttribute, IClientValidatable 
    { 
     private RequiredAttribute _innerAttribute = new RequiredAttribute(); 

     public string DependentProperty { get; set; } 
     public object TargetValue { get; set; } 

     public RequiredIfAttribute(string dependentProperty, object targetValue) 
     { 
      this.DependentProperty = dependentProperty; 
      this.TargetValue = targetValue; 
     } 

     protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
     { 
      var containerType = validationContext.ObjectInstance.GetType(); 
      var field = containerType.GetProperty(this.DependentProperty); 

      if (field != null) 
      { 
       var dependentvalue = field.GetValue(validationContext.ObjectInstance, null); 

       // compare the value against the target value 
       if ((dependentvalue == null && this.TargetValue == null) || 
        (dependentvalue != null && dependentvalue.Equals(this.TargetValue))) 
       { 
        if (!_innerAttribute.IsValid(value)) 
         return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName }); 
       } 
      } 

      return ValidationResult.Success; 
     } 

     public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
     { 
      var rule = new ModelClientValidationRule() 
      { 
       ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), 
       ValidationType = "requiredif", 
      }; 

      string depProp = BuildDependentPropertyId(metadata, context as ViewContext); 

      string targetValue = (this.TargetValue ?? "").ToString(); 
      if (this.TargetValue.GetType() == typeof(bool)) 
       targetValue = targetValue.ToLower(); 

      rule.ValidationParameters.Add("dependentproperty", depProp); 
      rule.ValidationParameters.Add("targetvalue", targetValue); 

      yield return rule; 
     } 

     private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext) 
     { 
      // build the ID of the property 
      string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(this.DependentProperty); 
      var thisField = metadata.PropertyName + "_"; 
      if (depProp.StartsWith(thisField)) 
       depProp = depProp.Substring(thisField.Length); 
      return depProp; 
     } 
    } 
} 

내가이 할 수있는 희망 특성 당신이

0

또한 단지 당신이에 날짜를 입력 필드에서 데이터를 얻을 수있는 도움과 해당 필드를 확인합니다.

이런 식으로 그냥 UI 쇼 숨기기 물건을 돕고있다/체크되지 않은 확인 말 확인란하지만, 유효성 검사 또는 페이로드의 일부가 아니다. 당신은 항상 그냥 숨겨진 또는 보이는 필드에서 날짜를 다시 얻을.

또한 컨트롤러 코드가 간단 해집니다.

관련 문제