首页 > 解决方案 > 如何将 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);
    }

标签: asp.netasp.net-mvc

解决方案


要将数据从一个操作传递到同一控制器中的另一个操作,您可以使用 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>  

推荐阅读