2017-11-21 1 views
-1

를 사용하지 않고 국가 이름에서 중복 확인 나는, 그런ASP.NET MVC는 - 모델 주석

저장소

 BackendEntities entity = new BackendEntities(); public void AddCountry(CountriesViewModel countryModel) { COUNTRIES2 newCountry = new COUNTRIES2() { COUNTRY_ID = countryModel.COUNTRY_ID, COUNTRY_CODE = countryModel.COUNTRY_CODE, COUNTRY_NAME = countryModel.COUNTRY_NAME, ACTION_STATUS = countryModel.ACTION_STATUS, CREATED_BY = countryModel.CREATED_BY, CREATED_DATE = countryModel.CREATED_DATE }; entity.COUNTRIES.Add(newCountry); entity.SaveChanges(); } 

을 만들기위한 컨트롤러 액션에 의해 사용되는 뷰 모델 및 저장소가 Create에 대한 Controller Action에서 Repository를 호출합니다. 내가 ACTION_STATUS 2

같지 않은 조건을 사용하여 중복 COUNTRY_NAME에 대한 유효성 검사를 어떻게

 public ActionResult Create(FormCollection collection, CountriesViewModel countries) 
    { 
    CountriesRepository countryRepo = new CountriesRepository(); 
     if (ModelState.IsValid) 
     { 
      try 
      { 
       // TODO: Add update logic here 
       countryRepo.AddCountry(countries); 
       //countryRepo. 
       var notif = new UINotificationViewModel() 
       { 
        notif_message = "Record saved successfully", 
        notif_type = NotificationType.SUCCESS, 
       }; 
       TempData["notif"] = notif; 
       return RedirectToAction("Index"); 
      } 
      catch (Exception e) 
      { 
       this.AddNotification("Country cannot be added.<br/> Kindly verify the data.", NotificationType.ERROR); 
      } 
     } 
     return View(countries); 
    } 

내가 모델 또는보기에서 작업을 수행하지 마십시오 컨트롤러 컨트롤러 또는 저장소에 있습니다. 아마도 컨트롤러에countryRepo.AddCountry (국가) 0120-전에 넣어야합니다.

+1

'부울 isDupe = db.COUNTRIES.Any (X => x.COUNTRY_NAME == countries.COUNTRY_NAME에서 당신의 나라 저장소 그런

public bool IsNameExist(string name, int id) { var result =entity.COUNTRIES.Any(c => c.COUNTRY_NAME == name && c.ACTION_STATUS != 2 && && c.COUNTRY_ID != id); return result; } 

에서 방법을 만들기 && –

+0

제어기 또는 저장소에 넣으십시오. – olugbenga

+0

컨트롤러에 넣을 수 있습니다. –

답변

0

컨트롤러

public ActionResult Create(FormCollection collection, CountriesViewModel countries) 
{ 
    ....... 
     if (countryRepo.IsNameExist(countries.COUNTRY_NAME, countries.COUNTRY_ID)) 
     { 
      ModelState.AddModelError("COUNTRY_NAME", "COUNTRY NAME already exist."); 
     } 
    ........ 
} 
+0

당신은 환상적입니다. 감사 – olugbenga