0

我在 MVC 中有一个具有以下定义的操作:

 public ActionResult Create(Club club)
    {       
        if (ModelState.IsValid)
        {
            Club clubFound = db.Clubs.FirstOrDefault(x => x.ClubName == club.ClubName);

            if (clubFound != null)
            {
                ViewBag.CountryID = new SelectList(db.Countries.OrderBy(x => x.CountryName), "CountryID", "CountryName");
                ModelState.AddModelError("", "The club already exists in the database.");
                return View();
            }
            else
            {
                db.Clubs.Add(club);
                db.SaveChanges();
                string message = MvcHtmlString.Create(@"Club added to the db successfully. <a href=""/"">Go back to home page.</a>").ToString();
                //TempData["SuccessMessage"] = "Club successfully added.";
                return Json(message, JsonRequestBehavior.AllowGet);
            }
        }

        return View();           
    }

如果所有数据都正常,则方法执行成功,一切正常。但是,当出现模型错误并且操作返回 View 时,它实际上会在视图中返回,所以我在另一个视图中有一个视图。我的问题是如何正常返回带有所有错误的视图,例如在正常的 POST 请求中?来自视图的数据始终来自 Ajax 表单,因此请求始终是异步的。

4

1 回答 1

0

我想您应该只返回模型并返回到触发操作的同一视图。当您向模型添加错误时,它必须返回到视图,而且我猜您可能必须在@Html.ValidationSummary()视图中添加一个。

就像是:

public ActionResult Create(Club club)
{       
    if (ModelState.IsValid)
    {
        Club clubFound = db.Clubs.FirstOrDefault(x => x.ClubName == club.ClubName);

        if (clubFound != null)
        {
            ViewBag.CountryID = new SelectList(db.Countries.OrderBy(x => x.CountryName), "CountryID", "CountryName");
            ModelState.AddModelError("", "The club already exists in the database.");
            return View(club);
        }
        else
        {
            db.Clubs.Add(club);
            db.SaveChanges();
            string message = MvcHtmlString.Create(@"Club added to the db successfully. <a href=""/"">Go back to home page.</a>").ToString();
            //TempData["SuccessMessage"] = "Club successfully added.";
            return Json(message, JsonRequestBehavior.AllowGet);
        }
    }

    return View(club);           
}
于 2013-08-19T19:05:37.310 回答