0

我在我的 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 和服务器名称已经存在?

4

1 回答 1

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");
于 2013-08-02T09:44:32.770 回答