在MVC4中向控制器中的所有动作传递一个固定id
本文关键字:id 一个 控制器 MVC4 | 更新日期: 2023-09-27 17:54:59
我有一个控制器ScoreController所以这个控制器中的所有动作都需要一个名为ScheduleId的id所以我必须*viewbag*并再次恢复。我的问题是我如何将此值设置为一个固定值和我所有的视图(即Edit,*Delete*,Create,*list*)和动作使用它而不传递?
控制器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EducationMVC.Models;
using EducationMVC.PresentationClass;
using EducationRepositor;
using DomainClasses;
namespace EducationMVC.Controllers
{
public class ScoreController : Controller
{
//
// GET: /Score/
private readonly ScoreRepository obj = new ScoreRepository();
PresentationClass.DateConverter objconverterDate=new DateConverter();
public ActionResult Index(string scheduleId)
{
List<ScoreStudentPresentation> objlist=new List<ScoreStudentPresentation>();
List<Score> model = obj.GetStudentlistOfSchedule(scheduleId);
foreach (Score t in model)
{
ScoreStudentPresentation objpres=new ScoreStudentPresentation();
objpres.ConfirmScore = objconverterDate.ConvertToPersianToShow(t.DateOfSubmit);
objpres.Family = t.Student.LastName;
objpres.Name = t.Student.Name;
objpres.Score = t.Point;
objpres.StudentNumber = t.Student.StudentId.ToString();
objpres.id = t.Id.ToString();
objlist.Add(objpres);
}
ViewBag.ScheduleId = scheduleId;
return View(objlist);
}
public ActionResult Create(string ScheduleId)
{
return View("Create");
// return View();
}
[HttpPost]
public ActionResult Create(Score score)
{
obj.AddNewScore(score);
obj.Save();
return RedirectToAction("Index", "Score");
}
public ActionResult Edit(int id)
{
return View(obj.FindScoreById(id));
}
[HttpPost]
public ActionResult Edit(Score score)
{
if (ModelState.IsValid)
{
obj.Update(score);
obj.Save();
}
return RedirectToAction("Index", "Score");
}
}
}
正如你所看到的,我传递了ScheduleId创建和索引,我必须为另一个动作,因为我需要ScheduleId。我想避免这种
问好。
这不是一个坏主意,如果你重写 onactionexecution 方法,并添加一个ViewBag项目,例如,ViewBag。在该方法中的ScheduleId,然后,在共享视图中使用hiddenInput,例如_Layout(可能在某些特定的地方,例如Score中的view folder)。
还可以在每个动作方法中定义一个名为scheduleId的参数,或者使用Request[" scheduleId "]