asp.net - 如何将 ViewBag 从控制器发送到特定的不同视图
问题描述
我想将 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();
}
以下是 home 控制器中存在但在 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);
}
解决方案
要将数据从一个操作传递到同一控制器中的另一个操作,您可以使用 Tempdata 而不是 ViewBag
喜欢
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>
推荐阅读
- c - 如何对包含 NaN 的 C 的数组进行排序
- c# - BsonDocument 到动态表达式或结果的内存缓存
- r - DT::replaceData() 在 observe() 中只执行一次
- google-sheets - 在不使用 JOIN 的情况下,在 Google 表格的逗号分隔值列中获取它们的唯一值和计数?
- javascript - 从 DOM 标头资源中提取 HTML 链接(没有 ID 或类)
- sms - Twilio 如何分割包含 url 的长消息?
- javascript - Javascript 滚动侦听器在 chrome 或 firefox 中不起作用
- python - 将分类变量绘制为堆积条形图
- java - Java - 动态访问嵌套的 JSONArray 值
- java - 确定文件编码并打印变音符号