我想将ViewBag从基于主控制器的控制器动作发送到其他视图,而不是应用视图:
public ActionResult Apply(ApplyForAJob applyForAJob)
{
applyForAJob.UserId = User.Identity.GetUserId();
applyForAJob.JobId = (int)Session["id"];
var check = db.ApplyForAJobs.Where(a => a.JobId.Equals(applyForAJob.JobId) && a.UserId.Equals(applyForAJob.UserId)).ToList();
if(check.Count < 1)
{
applyForAJob.ApplyDate = DateTime.Now;
db.ApplyForAJobs.Add(applyForAJob);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
ViewBag.Message = "You have already applied for this job";
}
return View();
}
以下是详细信息视图,该视图存在于家庭控制器中,但在apply方法中不存在
@using (Html.BeginForm("Apply","Home",FormMethod.Post))
{
@Html.AntiForgeryToken()
@ViewBag.Message
<div class="form-horizontal">
<h4>ApplyForAJob</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
类似于以下结构将很有帮助
return RedirectToAction("Details",ViewBag.Message= "You have already applied for this job");
详细操作:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Job.Find(id);
if (job == null)
{
return HttpNotFound();
}
Session["id"] = id;
return View(job);
}
public ActionResult Apply()
{
int id=10;
TempData["ID"] = id;
return RedirectToAction("Details");
}
public ActionResult Details()
{
int id = Convert.ToInt32(TempData["ID"]);// id will be 10;
ViewBag.DemoId= id;
return View();
}
以及您的详细信息视图中像这样使用
<p>Using ViewBag: @ViewBag.DemoId</p>