MVC中RedirectToAction的ModelState验证

时间:2018-08-09 11:53:02

标签: asp.net-mvc

我想在MVC中的ModelState.AddModelError上实现RedirectToAction。目前,我没有收到错误消息。谁能帮我吗?

if(ModelState.IsValid)
{  
     var HList = hDetails.HTrackerList().Where(x => x.AccId == user.AccountID && x.UserId == user.Id).Select(y=>y.HorseId).ToList();
     var datainList = HList.Contains(model.HorseId);

     if(!datainList)
     {            
         hDetails.InsertHorse(model);
     }
     else
     {
        ModelState.AddModelError("datainList", "Horse is already exist. Do you want to update it?");
     }
}

return RedirectToAction("Home");

在视图中:

@Html.ValidationMessage("datainList")

1 个答案:

答案 0 :(得分:1)

在您的发起人课程中:

public class YourController : Controller
{
   [HttpPost]
   public ActionResult TestMethod()
   {
       if(ModelState.IsValid)
       {  
         var HList = hDetails.HTrackerList().Where(x => x.AccId == user.AccountID && x.UserId == user.Id).Select(y=>y.HorseId).ToList();
         var datainList = HList.Contains(model.HorseId);

         if(!datainList)
         {            
            hDetails.InsertHorse(model);
         }
         else
         {
            TempData["datainListError"] = "Horse is already exist. Do you want to update it?";
         }
       }

      return RedirectToAction("Home");
   }
}

然后在家庭控制器中:

public class HomeController : Controller 
{
    public ActionResult Index()
    {
       if(TempData.ContainsKey("datainListError"))
       {
          ViewBag.ErrorMessage = TempData["datainListError"].ToString();
       }

      return View();

    }

}

然后在索引视图中:

@if(ViewBag.ErrorMessage != null)
{
   <div class="alert alert-danger">@ViewBag.ErrorMessage</div>
}