【发布时间】:2015-06-30 11:55:43
【问题描述】:
我正在使用 MVC 和实体框架创建 ASP.NET Web 应用程序。当用户打卡或打卡时,我有两个不同的成功消息传递给索引操作。当用户打卡时成功消息将正确打印,但当用户出于某种原因下班时不会。
操作非常相似,我使用了所有相同的约定,所以我无法弄清楚为什么一个会打印而另一个不会。我已经尝试过调试并且没有危险信号,并且数据库中的所有内容都按照应有的方式进行了更新。不能将多个 TempData 变量传递给同一个动作吗?
以下是相关代码:
控制器
// GET: TimeClocks
public ActionResult Index()
{
ViewBag.ClockInSuccess = TempData["ClockInSuccess"];
ViewBag.ClockOutSuccess = TempData["ClockOutSuccess"];
return View();
}
[HttpPost]
public ActionResult ClockIn(TimeClock timeClock)
{
if(db.TimeClocks.ToList().Count == 1)
{
ModelState.AddModelError("ExistsError", "You already clocked in at" + timeClock.ClockIn);
}
string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
timeClock.ApplicationUser = currentUser;
timeClock.ClockIn = DateTime.Now;
if (ModelState.IsValid)
{
db.TimeClocks.RemoveRange(db.TimeClocks.ToList());
db.TimeClocks.Add(timeClock);
db.SaveChanges();
TempData["ClockInSuccess"] = "You clocked in successfully at " + timeClock.ClockIn;
return RedirectToAction("Index");
}
return RedirectToAction("Index", timeClock);
}
[HttpPost]
public ActionResult ClockOut(TimeClock timeClock)
{
timeClock = db.TimeClocks.FirstOrDefault();
if(timeClock.ClockIn == null)
{
ModelState.AddModelError("NullError", "You must clock in before you can clock out.");
return RedirectToAction("Index");
}
timeClock.ClockOut = DateTime.Now;
if (ModelState.IsValid)
{
db.Entry(timeClock).State = EntityState.Modified;
db.SaveChanges();
TempData["ClockOutSuccess"] = "You clocked out successfully at " + timeClock.ClockOut;
return RedirectToAction("Index");
}
return RedirectToAction("Index", timeClock);
}``
查看
@model FinalProject.Models.TimeClock
@{
ViewBag.Title = "Create";
}
<h2>Employee Time Clock</h2>
@using (Html.BeginForm("ClockIn", "TimeClocks"))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Clock In" class="btn btn-lg" />
</div>
</div>
</div>
}
@using (Html.BeginForm("ClockOut", "TimeClocks"))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Clock Out" class="btn btn-lg" />
</div>
</div>
</div>
}
@{
if (@ViewBag.ClockInSuccess != "")
{
<p class="alert-success">@ViewBag.ClockInSuccess</p>
}
else if (@ViewBag.ClockOutSuccess != "")
{
<p class="alert-success">@ViewBag.ClockOutSuccess</p>
}
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
【问题讨论】:
-
您的代码没有意义。您的视图有
@Html.ActionLink("Back to List", "Index"),表明您显示的视图不是Index视图。在您的 post 方法中,如果模型无效,那么您正在调用return RedirectToAction("Index", timeClock);但Index()方法不接受参数,因此第二个参数没有意义(无论如何它都不会起作用)。非常不清楚您尝试做什么以及您期望的结果是什么。
标签: c# entity-framework asp.net-mvc-5 ef-code-first