Asp.net mvc ASP.NET MVC-在不使用模型注释的情况下检查国家/地区名称是否重复
我有一个ViewModel和存储库,控制器操作用于创建 存储库Asp.net mvc ASP.NET MVC-在不使用模型注释的情况下检查国家/地区名称是否重复,asp.net-mvc,Asp.net Mvc,我有一个ViewModel和存储库,控制器操作用于创建 存储库 BackendEntities entity = new BackendEntities(); public void AddCountry(CountriesViewModel countryModel) { COUNTRIES2 newCountry = new COUNTRIES2() { COUNTRY_ID = countryModel
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();
}
然后,我从控制器操作调用存储库来创建。
控制器
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);
}
public ActionResult创建(FormCollection集合、CountriesViewModel国家/地区)
{
CountriesRepository countryRepo=新的CountriesRepository();
if(ModelState.IsValid)
{
尝试
{
//TODO:在此处添加更新逻辑
countryRepo.AddCountry(多个国家);
//countryRepo。
var notif=新的UINotificationViewModel()
{
notif_message=“记录保存成功”,
notif_type=NotificationType.SUCCESS,
};
TempData[“notif”]=notif;
返回操作(“索引”);
}
捕获(例外e)
{
此.AddNotification(“无法添加国家/地区。
请验证数据。”,NotificationType.ERROR);
}
}
返回视图(国家);
}
如果操作状态不等于2,如何使用条件验证重复的国家/地区名称
我不想从模型或视图中执行,而是在控制器或存储库中执行。
可能将其放在控制器中的countryRepo.AddCountry(国家)之前。在您的国家/地区存储库中创建一个方法
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;
}
然后在你的控制器里
public ActionResult Create(FormCollection collection, CountriesViewModel countries)
{
.......
if (countryRepo.IsNameExist(countries.COUNTRY_NAME, countries.COUNTRY_ID))
{
ModelState.AddModelError("COUNTRY_NAME", "COUNTRY NAME already exist.");
}
........
}
bool isDupe=db.COUNTRIES.Any(x=>x.COUNTRY\u NAME==COUNTRIES.COUNTRY\u NAME&&x.ACTION\u STATUS!=2)代码>请将其放入控制器或存储库如果要避免重复,您可以将其放入数据库中的controllera约束也是一件好事。问题是我不想直接从控制器(例如数据库)访问数据库。这就是我使用ViewModel和Repository的原因。那么,我如何根据我所拥有的整合它呢。谢谢你太棒了。谢谢