如何创建绑定到对象的文本框

时间:2018-12-09 18:02:39

标签: c# entity-framework asp.net-mvc-4 razor

我使用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);
    }

需求-> 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,以显示保存在session对象中的当前登录的雇员。

我尝试了很多事情,例如从控制器中将Employe对象保存在模型中,就像您在上面的控制器代码中看到的那样,但是它没有用,因为视图不会将整个对象保存到我的理解后,当我提交时,它会覆盖Employe对象,只保留name属性。它适用于datestatus,因为它们是基本对象,但不适用于Employe

我试图尽最大的能力来解释,我对ASP.NET MVC还是很陌生。如果您希望我提供更多信息,请告诉我。

0 个答案:

没有答案