私はASP.NET MVC でこのチュートリアルに"MovieType"
従っています。具体的には、次のように Razor View にString を提供すると記載されてい@Html.DropDownList("MovieType")
ます。ViewBag
IEnumerable<SelectListItem>
それはうまくいきます。
ただし、[HttpPost]
属性を使用してメソッドでユーザーが選択した値を取得できません。
ここに私のコードと私がこれまでに試したことがあります。
コントローラ
public class ProductController : Controller
{
private readonly ProductRepository repository = new ProductRepository();
// Get: /Product/Create
public ActionResult Create()
{
var categories = repository.FindAllCategories(false);
var categorySelectListItems = from cat in categories
select new SelectListItem()
{
Text = cat.CategoryName,
Value = cat.Id.ToString()
};
ViewBag.ListItems = categorySelectListItems;
return View();
}
[HttpPost]
public ActionResult Create(Product product)
{
/** The following line is not getting back the selected Category ID **/
var selectedCategoryId = ViewBag.ListItems;
repository.SaveProduct(product);
return RedirectToAction("Index");
}
}
Razor cshtml ビュー
@model Store.Models.Product
<h2>Create a new Product</h2>
@using (@Html.BeginForm())
{
<p>Product Name:</p>
@Html.TextBoxFor(m => m.ProductName)
<p>Price</p>
@Html.TextBoxFor(m => m.Price)
<p>Quantity</p>
@Html.TextBoxFor(m => m.Quantity)
<p>Category</p>
@Html.DropDownList("ListItems")
<p><input type="submit" value="Create New Product"/></p>
}
のオーバーロードを試してみましたDropDownList
が、ユーザーが選択している値を取り戻すことができません。
誰かが私に欠けているものを見たり、アイデアや提案があれば、とても感謝しています. ありがとう!
アップデート
投稿Product
モデル。これは、.edmx を作成したときに Entity Framework によって自動生成されたことに注意してください。
namespace Store.Models
{
using System;
using System.Collections.Generic;
public partial class Product
{
public long Id { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public System.DateTime DateAdded { get; set; }
public Nullable<long> CategoryId { get; set; }
public virtual Category Category { get; set; }
}
}