我在asp.net mvc web应用程序中有以下代码作为动作方法的一部分: -
try
{
if (ModelState.IsValid)
{
if (!(repository.IsIPUnique(serverToEdit.TechnologyIP.IPAddress, 0)))
{
ModelState.AddModelError("TechnologyIP.IPAddress", "Error occured. The Same IP might already assinged.");
ViewBag.Customers = repository.FindAccountDefinition(null).ToList();
ViewBag.ServerModels = repository.AllServerModel().ToList();
ViewBag.DataCenters = repository.AllDataCenter().ToList();
ViewBag.Racks = repository.AllRacks().ToList();
ViewBag.OperatingSystem = repository.AllOperatingSystem().ToList();
ViewBag.TechStatus = repository.AllTechnologyStatus().ToList();
ViewBag.TechBackUpStatus = repository.AllTechnologyBackupStatus().ToList();
ViewBag.TechRole = repository.AllTechnologyRole().ToList();
return View(serverToEdit);
}
if (!(repository.IsServerNameUnique(serverToEdit.Server.Name, 0)))
{
ModelState.AddModelError("Server.Name", "Error occured. The Same Server Name might already assinged.");
ViewBag.Customers = repository.FindAccountDefinition(null).ToList();
ViewBag.ServerModels = repository.AllServerModel().ToList();
ViewBag.DataCenters = repository.AllDataCenter().ToList();
ViewBag.Racks = repository.AllRacks().ToList();
ViewBag.OperatingSystem = repository.AllOperatingSystem().ToList();
ViewBag.TechStatus = repository.AllTechnologyStatus().ToList();
ViewBag.TechBackUpStatus = repository.AllTechnologyBackupStatus().ToList();
ViewBag.TechRole = repository.AllTechnologyRole().ToList();
return View(serverToEdit);
}
repository.InsertOrUpdateServer(serverToEdit.Server,serverToEdit.TechnologyIP,User.Identity.Name);
repository.Save();
return RedirectToAction("Index");
}
目前我有两种服务方法(IsIPUnique和IsServerNameUnique),但我不知道如何将两种服务方法连接在一起,而不是使用viewBag构建下拉列表的单独代码,并显示两种模型状态错误消息(而不是单独的错误消息)给用户带来IP& server-name已经存在?
答案 0 :(得分:0)
如果向模型状态添加一些错误,则IsValid属性将变为false。你可以用它。
if (!(repository.IsIPUnique(serverToEdit.TechnologyIP.IPAddress, 0)))
{
ModelState.AddModelError("...", "...");
}
if (!...)
{
ModelState.AddModelError("...", "...");
}
if (!ModelState.IsValid)
{
ViewBage.XXX = ...;
return View();
}
repository.InsertOrUpdateServer(serverToEdit.Server,serverToEdit.TechnologyIP,User.Identity.Name);
repository.Save();
return RedirectToAction("Index");