我使用Entity Framework为我的类生成我的控制器和视图 .
这就是我所拥有的:
DemandeController.cs
(控制器):
public ActionResult Create()
{
Demande model = new Demande();
model.date = DateTime.Now;
model.status = "en cours";
Employe emp = (Employe)Session["currentUser"];
model.Employe = emp;
ViewBag.ServiceID = new SelectList(db.Services, "id", "nom");
ViewBag.EmployeID = new SelectList(db.Employes, "matricule", "nom");
return View(model);
}
Demande - > Create.cshtml
(查看)
<div class="editor-label">
@Html.LabelFor(model => model.EmployeID, "Employe")
</div>
<div class="editor-field">
@Html.DropDownList("EmployeID", String.Empty)
@Html.ValidationMessageFor(model => model.EmployeID)
</div>
Employe
课程:
public partial class Employe
{
public Employe()
{
this.ActivityLogs = new HashSet<ActivityLog>();
this.Demandes = new HashSet<Demande>();
}
public int matricule { get; set; }
public int DepartementID { get; set; }
public string nom { get; set; }
public string prenom { get; set; }
public string telephone { get; set; }
public string adresse { get; set; }
public string fonction { get; set; }
public string username { get; set; }
public string password { get; set; }
public string role { get; set; }
public Nullable<bool> isAdmin { get; set; }
public virtual ICollection<ActivityLog> ActivityLogs { get; set; }
public virtual ICollection<Demande> Demandes { get; set; }
public virtual Departement Departement { get; set; }
}
Demande
课程:
public partial class Demande
{
public int id { get; set; }
public int EmployeID { get; set; }
public int ServiceID { get; set; }
public Nullable<System.DateTime> date { get; set; }
public string status { get; set; }
public string details { get; set; }
public virtual Service Service { get; set; }
public virtual Employe Employe { get; set; }
}
默认情况下,因为我有很多员工,视图会生成 dropdownlist
,我必须选择员工姓名 . 这没有问题 .
但是,我正在尝试将 dropdownlist
更改为 textbox
,它将显示当前登录的employees,该对象保存在 session
对象中 .
我尝试了很多东西,例如从Controller中保存模型中的 Employe
对象,就像你在上面的Controller代码中看到的那样,但它不起作用,因为View没有将整个对象保存到我的理解中所以当我提交时,它覆盖 Employe
对象并仅保留name属性 . 它适用于 date
和 status
,因为它们是基本对象,但不适用于 Employe
.
我试着向最好的容量解释,我是ASP.NET MVC的新手 . 如果您希望我提供任何进一步的信息,请告诉我 .