簡體   English   中英

帶有Html.DropDownList的.NET MVC 5 FORM麻煩

[英].NET MVC 5 FORM Troubles with Html.DropDownList

我的任務是創建一個連接到本地MS SQL服務器的.NET MVC表單。 該表格應注意為學生和課程注冊數據。 在數據庫中,有簡單的表格“學生”,“學生課程”,“課程”和“教師”。 由於我必須獲得多個模型的信息,因此創建了一個ViewModel,它是:

public class ViewModelVM
    {
        public Teacher Teacher { get; set; }
        public Student Student { get; set; }
        public Cours Cours { get; set; }
    }

在數據庫中,我已經有一些課程,我的目標是創建DropDownList,因此學生必須在其中選擇。

@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    <div class="form-group">
        <label>Student Firstname:</label>
        @Html.TextBoxFor(x => x.Student.FirstName, new { @class = "formcontrol" })
    </div>
    <div class="form-group">
        <label>Student Birthdate:</label>
        @Html.TextBoxFor(x => x.Student.BirthDate, new { @class = "formcontrol" })
    </div>
    <div class="form-group">
        <label>Student FNum:</label>
        @Html.TextBoxFor(x => x.Student.Fnum, new { @class = "formcontrol" })
    </div>


  **<div class="form-group">
            <label>Studet's Courses</label>
            // I want to make something like this
            // @Html.DropDownListFor(x => x.Student.Courses, new[] {
 new SelectListItem() {Text = "C++", Value = bool.TrueString},
 new SelectListItem() {Text = "c#", Value = bool.FalseString}}, 
                        "Choose course", new { @class = "formcontrol" })

        </div>**


    <div class="form-group">
        <label>Teacher Fnum:</label>
        @Html.TextBoxFor(x => x.Teacher.Fnum, new { @class = "formcontrol" })
    </div>
    <div class="form-group">
        <label>Course Signature:</label>
        @Html.TextBoxFor(x => x.Cours.Signature, new { @class = "formcontrol" })
    </div>
    <div class="form-group">
        <label>Course.Teacher Fnum data:</label>
        @Html.TextBoxFor(x => x.Cours.Teacher.Fnum, new { @class = "formcontrol" })
    </div>
    <div class="text-center">
        <input class="btn btn-success" type="submit"
               value="Submit Info" />
    </div>
}

重要! :DropDownList中的項目將不是新的,它們將已經存在於數據庫中。

我的問題是,我現在該怎么寫這個DropDown,因為現在不正確。 Value = bool.TrueString ,僅是示例文本,我想輸入以下內容: Model.Student.Courses.Where(CourseName == 'C++');

這是一個基於MVC音樂商店示例的模型。 在您看來,使用以下代碼:

@Html.DropDownList("DropDownStudent", "Select student", new { @class = "formcontrol" })

現在,您需要在控制器內部的action方法中使用ViewData使用值填充組合框。 例如:

public ActionResult Index()
{   
    var List<string> students= new List<string>();
    students.Add("Amanda");
    students.Add("Heather");
    students.Add("Jane");
    students.Add("Jonh");
    students.Add("Mark");         

    ViewBag.DropDownStudent = new SelectList(students);
    return View();
}

您可能要用數據庫中的值填充下拉列表,因此應通知“值”和“文本”列:

ViewBag.DropDownStudent = new SelectList(yourList, "student_id", "student_name");

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM