首页 > 解决方案 > 如何创建绑定到对象的文本框

问题描述

我使用 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我必须选择员工姓名的位置。这没有问题。

但是,我正在尝试将其更改dropdownlisttextbox将显示保存在session对象中的当前登录的员工。

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

我试图尽最大努力解释,我对 ASP.NET MVC 还很陌生。如果您希望我提供任何进一步的信息,请告诉我。

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

解决方案


推荐阅读