1

こんにちは私はMVC 3アプリケーションで働いています。次のコードでフォームを作成しています。

@model Xrm.Student
@{
ViewBag.Title = "Create Student Record";
 }
@using (Html.BeginForm("Create", "Student", FormMethod.Post))
{
    <div class="editor-label">
         @Html.LabelFor(model => @Model.FirstName)
    </div>
    <div class="editor-field">                                      
         @Html.EditorFor(model => @Model.FirstName)
         @Html.ValidationMessageFor(model => @Model.FirstName)
    </div>
<div>
    <input id="Submit1" type="submit" value="Submit" />
</div>
}

pubjects を入力する必要がある Firsname フィールドの下に新しいドロップダウンを追加したいと考えています。サブジェクトは別のエンティティです。私は非常に簡単かもしれませんが、私はMVCの初心者なので、ここで立ち往生しています。誰でもそれを達成する方法を教えてください。

感謝と敬意

4

1 に答える 1

4

ビューモデルを定義します:

public class MyViewModel
{
    public Student Student { get; set; }

    [DisplayName("Subject")]
    [Required]
    public string SubjectId { get; set; }

    public IEnumerable<Subject> Subjects { get; set; }
}

次に、コントローラーにデータを入力させ、このビュー モデルをビューに渡します。

public ActionResult Create()
{
    var model = new MyViewModel();
    model.Student = new Student();
    model.Subjects = db.Subjects;
    return View(model);
}

最後に、ビュー モデルに強く型付けされたビューを作成します。

@model MyViewModel
@{
    ViewBag.Title = "Create Student Record";
}
@using (Html.BeginForm())
{
    <div class="editor-label">
         @Html.LabelFor(x => x.Student.FirstName)
    </div>
    <div class="editor-field">                                      
         @Html.EditorFor(x => x.Student.FirstName)
         @Html.ValidationMessageFor(x => x.Student.FirstName)
    </div>

    <div class="editor-label">
         @Html.LabelFor(x => x.SubjectId)
    </div>
    <div class="editor-field">                                      
         @Html.DropDownListFor(
             x => x.SubjectId, 
             new SelectList(Model.Subjects, "Id", "Name"),
             "-- Subject --"
         )
         @Html.ValidationMessageFor(x => x.SubjectId)
    </div>

    <div>
        <input type="submit" value="Submit" />
    </div>
}

SelectList に使用した と の値は、明らかに、ドロップダウンの各オプションの ID とテキストをそれぞれバインドするために使用するクラスの既存のプロパティである必要があり"Id"ます。"Name"Subject

于 2012-04-17T14:37:27.453 に答える