我有一个asp.net mvc4应用程序,其中我想添加一个javascript警报
视图中的
@{
try
{
string str = ViewData["Alert"].ToString();
<script>alert(@str); </script>
}
catch { }
}
在我的控制器中
public ActionResult Reserver() {
User u = (User)Session["user"];
if (u == null) return RedirectToAction("Index", "Home");
string _fonction = _equipe.Get_Status_User(u.Id_user);
if (_fonction != "User") return RedirectToAction("Index", "Home");
int id_affaire = int.Parse(Request.Params["id_affaire"]);
int id_vehicule = int.Parse(Request.Params["matricule"]);
int periode;
try
{
periode = int.Parse(Request.Params["periode"]);
}
catch { periode = 0; }
int jours;
try
{
jours = int.Parse(Request.Params["nbr_jours"]);
}
catch { jours = 0; }
string date;
try
{
date = Request.Params["date"];
string[] tab = date.Split('/');
date = tab[2] + "-" + tab[0] + "-" + tab[1];
}
catch {
ViewData["Alert"] = "Veuillez préciser la date stp";
return RedirectToAction("Reserver_Véhicule");
}
if (DateTime.Parse(date) <= DateTime.Now) { ViewData["Alert"] = "Veuillez taper une date valide stp"; return RedirectToAction("Reserver_Véhicule"); }
Owner resp = new Owner();
if (resp.Exist_Affectation(DateTime.Parse(date), periode, id_vehicule)) { ViewData["Alert"] = "La véhicule est indisponible"; return RedirectToAction("Reserver_Véhicule"); }
if(jours > 0 )
{
for (int i = 0; i < jours; i++)
{
if (resp.Exist_Affectation(DateTime.Parse(date).AddDays(i), 0, id_vehicule)) { ViewData["Alert"] = "La véhicule est indisponible"; return RedirectToAction("Reserver_Véhicule"); }
if (resp.Exist_Affectation(DateTime.Parse(date).AddDays(i), 1, id_vehicule)) { ViewData["Alert"] = "La véhicule est indisponible"; return RedirectToAction("Reserver_Véhicule"); }
}
for (int i = 0; i < jours; i++)
{
resp.Create_Affectation(u.Id_user, id_affaire, id_vehicule, DateTime.Parse(date).AddDays(i), 1);
resp.Create_Affectation(u.Id_user, id_affaire, id_vehicule, DateTime.Parse(date).AddDays(i), 2);
}
return View("Index");
}
if (periode > 0)
{
if (resp.Exist_Affectation(DateTime.Parse(date), periode, id_vehicule)) { ViewData["Alert"] = "La véhicule est indisponible"; return RedirectToAction("Reserver_Véhicule"); }
resp.Create_Affectation(u.Id_user, id_affaire, id_vehicule, DateTime.Parse(date), periode);
return View("Index");
}
bool b1 = resp.Exist_Affectation(DateTime.Parse(date), 1, id_vehicule);
bool b2 = resp.Exist_Affectation(DateTime.Parse(date), 2, id_vehicule);
if (b1 == true || b2 == true) { ViewData["Alert"] = "La véhicule est indisponible"; return RedirectToAction("Reserver_Véhicule"); }
resp.Create_Affectation(u.Id_user, id_affaire, id_vehicule, DateTime.Parse(date), 1);
resp.Create_Affectation(u.Id_user, id_affaire, id_vehicule, DateTime.Parse(date), 2);
return View("Index");
}
问题是尽管控制器中ViewData["Alert"]
的值不为空,但警报仍未出现。
我该如何解决这个问题?
答案 0 :(得分:0)
我将ViewData
更改为TempData
并且可以正常工作:
@{
try
{
string str = TempData["Alert"].ToString();
<script>alert('@Html.Raw(@str)');
</script>
}
catch { }
}
我找到了解决方案in this link