0

EF와 함께 코드 우선을 사용하고 있습니다. 검증은 System.NullReferenceException 오류와 함께 드롭 다운 목록에서 실패한 것 같습니다 : 객체 참조가 객체의 인스턴스로 설정되지 않았습니다. 이것은 레코드를 저장할 때 발생하며 유효성 검사를 테스트하기 위해 컨트롤을 비워 둡니다. 드롭 다운 목록 자체에 선택 항목이 있더라도 발생합니다.유효성 검사에 실패했습니다. MVC

public ActionResult Create() 
{ 
    var e = iEmployeeRepository.GetAll(); 
    var visitorLogViewModel = new VisitorLogViewModel 
    { 
     Employees = e.Select(x => new SelectListItem 
     { 
      Value = x.EmployeeID, 
      Text = x.EmployeeName 
     }) 
    }; 
    return View(visitorLogViewModel); 
} 

// 
// POST: /VisitorLogs/Create 

[HttpPost] 
public ActionResult Create(VisitorLog visitorlog) 
{ 
    if (ModelState.IsValid) { 
     iVisitorlogRepository.Add(visitorlog); 
     iVisitorlogRepository.Save(); 
     return RedirectToAction("Search"); 
    } else { 
     return View(); 
    } 
} 

그리고 내 뷰 모델 :

여기
<div class="editor"> 
    @Html.LabelFor(model => model.EmployeeID) 
    @Html.TextBoxFor(model => model.EmployeeID, new { style = "width: 250px;" }) 
    @Html.ValidationMessageFor(model => model.EmployeeID) 
</div> 

내 생성 컨트롤러 작업입니다 : 내가 텍스트 상자의 유효성 검사가 작동 사용하는 경우

<div class="editor"> 
    @Html.LabelFor(model => model.EmployeeID) 
    @Html.DropDownListFor(model => model.EmployeeID, new SelectList(Model.Employees, "Value", "Text")) 
    @Html.ValidationMessageFor(model => model.EmployeeID) 
</div> 

: 여기

내보기의 일부입니다 :

public class VisitorLogViewModel 
{ 
    public int Id { get; set; } 

    [Display(Name = "Visitor Name")] 
    public string VisitorName { get; set; } 

    [Display(Name = "Company Name")] 
    public string CompanyName { get; set; } 

    [Required(ErrorMessage = "Employee ID is required.")] 
    [Display(Name = "GB Employee")] 
    public string EmployeeID { get; set; } 

    [Display(Name = "Visit Reason")] 
    public string VisitReason { get; set; } 

    [Display(Name = "Time In")] 
    public DateTime TimeIn { get; set; } 

    [Display(Name = "Time Out")] 
    public DateTime TimeOut { get; set; } 

    [Display(Name = "GB Employee")] 
    public string EmployeeName { get; set; } 

    public IEnumerable Employees { get; set; } 
    public VisitorLog VisitorLog { get; set; } 
} 

그리고 검증을위한 내 부분 모델 :

[MetadataType(typeof(VisitorLogMetaData))] 
public partial class VisitorLog 
{ 

} 

public class VisitorLogMetaData 
{ 
    [Required(ErrorMessage = "Visitor name is required.")] 
    [MaxLength(128)] 
    public string VisitorName { get; set; } 

    [Required(ErrorMessage = "Company name is required.")] 
    [MaxLength(128)] 
    public string CompanyName { get; set; } 

    [Required(ErrorMessage = "GB Employee is required.")] 
    [MaxLength(128)] 
    public string EmployeeID { get; set; } 

    [Required(ErrorMessage = "Visit reason is required.")] 
    [MaxLength(254)] 
    public string VisitReason { get; set; } 

    [Required(ErrorMessage = "Time in is required.")] 
    public DateTime TimeIn { get; set; } 

    [Required(ErrorMessage = "Time out reason is required.")] 
    public DateTime TimeOut { get; set; } 
} 

그리고 마지막으로 내 모델 : 나는 거기에 DropDownListFor에 대한 MVC 면도기에서 문제를했지만, 난 그 경우 모르는 읽어

public partial class VisitorLog 
{ 
    public int Id { get; set; } 
    public string VisitorName { get; set; } 
    public DateTime TimeIn { get; set; } 
    public DateTime TimeOut { get; set; } 
    public string CompanyName { get; set; } 
    public string EmployeeID { get; set; } 
    public string VisitReason { get; set; } 

    // Navigation properties 
    [ForeignKey("EmployeeID")] 
    public virtual Employee Employee { get; set; } 
} 

내 상황에 적용됩니다. 나는 해결책의 일부를 시도했고 그들은 나를 위해 일하지 않았다. 4.5 프레임 워크를 사용하고 있습니다.

감사합니다.

편집 : 내가 발견

한 가지 내가 페이지를 제출하고 오류가 드롭 다운 요소를 중지 할 때 :

@Html.DropDownListFor(model => model.EmployeeID, new SelectList(Model.Employees, "Value", "Text")) 

가 잃어버린 것처럼 Model.Employees의 모델은, null의 그 페이지가 제출 될 때 바인딩.

답변

0

좋아, 나는 수업에 몇 가지 근본적인 변화를했습니다. 먼저 컨트롤러에서 post 메서드를 변경했습니다. 이전에 지금 내 저장소를 통해 저장하기 전에 뷰 모델을 통과하고 모델에 매핑하고, 이후에 모델을 통과했다 :

// 
    // POST: /VisitorLogs/Create 

    [HttpPost] 
    public ActionResult Create(VisitorLogViewModel visitorLogViewModel) 
    { 
     var e = iEmployeeRepository.GetAll(); 
     VisitorLog visitorLog = new VisitorLog(); 
     visitorLog.Id = visitorLogViewModel.Id; 
     visitorLog.VisitorName = visitorLogViewModel.VisitorName; 
     visitorLog.CompanyName = visitorLogViewModel.CompanyName; 
     visitorLog.EmployeeID = visitorLogViewModel.EmployeeID; 
     visitorLog.TimeIn = visitorLogViewModel.TimeIn; 
     visitorLog.TimeOut = visitorLogViewModel.TimeOut; 
     visitorLog.VisitReason = visitorLogViewModel.VisitReason; 
     visitorLogViewModel.Employees = new SelectList(e, "EmployeeID", "EmployeeName"); 

     if (ModelState.IsValid) 
     { 
      iVisitorlogRepository.Add(visitorLog); 
      iVisitorlogRepository.Save(); 
      return RedirectToAction("Search"); 
     } else { 
      return View(visitorLogViewModel); 
     } 
    } 

다음, 나는 "필요한"속성 (확인)를 추가했다 보기 모델로 :

public class VisitorLogViewModel 
{ 
    public int Id { get; set; } 

    [Required(ErrorMessage = "Visitor name is required.")] 
    [MaxLength(128)] 
    [Display(Name = "Visitor Name")] 
    public string VisitorName { get; set; } 

    [Required(ErrorMessage = "Company name is required.")] 
    [MaxLength(128)] 
    [Display(Name = "Company Name")] 
    public string CompanyName { get; set; } 

    [Required(ErrorMessage = "GB Employee is required.")] 
    [MaxLength(16)] 
    [Display(Name = "GB Employee")] 
    public string EmployeeID { get; set; } 

    [Required(ErrorMessage = "Visit Reason is required.")] 
    [MaxLength(254)] 
    [Display(Name = "Visit Reason")] 
    public string VisitReason { get; set; } 

    [Display(Name = "Time In")] 
    public DateTime TimeIn { get; set; } 

    [Display(Name = "Time Out")] 
    public DateTime TimeOut { get; set; } 

    [Display(Name = "GB Employee")] 
    public string EmployeeName { get; set; } 

    public SelectList Employees { get; set; } 
} 

가장 효과적인 방법인지는 모르겠지만 지금은 모두 작동합니다. 누군가이 방법에 뭔가 잘못되었다고 생각되면 알려주십시오.

관련 문제