0

現在、ViewBag を使用してビューからデータを取得し、モデルを更新しています。選択したアイテムを取得するドロップダウンリストを使用しており、コントローラーで選択した「顧客モデル」を更新しています。これは良い方法ではないことはわかっています...フォームコレクションパラメーターを使用せずに、ドロップダウンリストの選択で「顧客モデル」を更新する方法を教えてください。

コントローラ

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Customer customer, FormCollection form)
    {
        if (ModelState.IsValid)
        {
            // Get selectected title from dropdownlist
            customer.Title = form["TitleDropDownList"];

            db.Customers.Add(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(customer);
    }

意見

    <tr>
        <td>
            @Html.LabelFor(model => model.Title)
        </td>
        <td>
            @Html.DropDownList("TitleDropDownList")
            @Html.ValidationMessageFor(model => model.Title)
        </td>
    </tr>

私のGetメソッドは...

    public ActionResult Create()
    {

        // Create title dropdownlist list for new customers
        List<SelectListItem> titleDropDownList = new List<SelectListItem>();
        titleDropDownList.Add(new SelectListItem { Text = "Mr", Value = "Mr" });
        titleDropDownList.Add(new SelectListItem { Text = "Mrs", Value = "Mrs" });
        titleDropDownList.Add(new SelectListItem { Text = "Miss", Value = "Miss" });
        titleDropDownList.Add(new SelectListItem { Text = "Ms", Value = "Ms" });
        ViewBag.TitleDropDownList = titleDropDownList;

        return View();
    }
4

1 に答える 1

0

メソッドを static に変更して List を返す場合

public static List<SelectListItem> Create(){
    //Build List
    return titleDropDownList;
}

ビューのドロップダウンを次のように変更できます

@Html.DropDownListFor(x => x.Title, PathToController.Create(), "Select One")

うまくいけば、これが役に立ちます。

于 2013-09-30T22:42:23.000 に答える