2013-04-03 87 views
1

我有一個創建頁面並有下拉列表。我的問題是,當我提交表單時,下拉列表爲空。請幫助。這是我的代碼。當提交表單時(MVC3)DropdownList爲空

public class Product 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public string Description { get; set; } 
     public List<SelectListItem> Types { get; set; } 
    } 

創建(GET)

 // GET: /Products/Create 

     public ActionResult Create(string id) 
     { 
      List<Product> products; 
      if (Session["products"] != null) products = Session["products"] as List<Product>; 
      else products = new List<Product>(); 
      var product = products.FirstOrDefault(x => id != null && x.Id == int.Parse(id))??new Product(); 
      var types = new List<SelectListItem>(); 
      var type = new SelectListItem { Selected = false, Value = "0", Text = "Electronics" }; 
      types.Add(type); 
      type = new SelectListItem { Selected = false, Value = "1", Text = "Non-Electronics" }; 
      types.Add(type); 
      product.Types = types.Select(x => new SelectListItem { Value = x.Value, Text = x.Text }).ToList(); 
      return View(product); 
     } 

查看

@model MVCViewState.Models.Product

@{ 
    ViewBag.Title = "Create"; 
} 

<h2>Create</h2> 

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <legend>Product</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Name) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Name) 
      @Html.ValidationMessageFor(model => model.Name) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Description) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Description) 
      @Html.ValidationMessageFor(model => model.Description) 
     </div> 
     <div class="editor-label"> 
      @Html.LabelFor(model => model.Types) 
     </div> 
     <div class="editor-field"> 
      @Html.DropDownListFor(model => model.Types, Model.Types) 
      @Html.ValidationMessageFor(model => model.Types) 
     </div> 
     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

創建(POST)

enter image description here enter image description here

回答

4

我覺得你的意圖是捕獲的選擇Type值。所以,你需要的東西是這樣的:

public class Product 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
    public List<SelectListItem> Types { get; set; } 
    public int TypeId { get; set; } // the selected type from the dropdown 
} 

而且對你的看法,你需要這樣的:

@Html.DropDownListFor(model => model.TypeId, Model.Types) 
+0

常見的問題......也許代碼優先 –

+0

感謝這真的是我要找的 –

+0

您受歡迎的 –