2013-10-28 73 views
0

我有這些模型:如何在MVC創建下拉4

public class Product 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } 
    [Required] 
    [Display(Name = "Ürün Adı")] 
    public string Name { get; set; } 
    [Required] 
    [Display(Name = "Açıklama")] 
    public string Description { get; set; } 
    [Required] 
    [Display(Name = "Fiyat")] 
    public decimal Price { get; set; } 
    [Required] 
    [Display(Name = "İndirim")] 
    public decimal Discount { get; set; } 
    [Required] 
    [Display(Name = "İndirim Geçerli Mi?")] 
    public bool IsDiscountActive { get; set; } 
    [Required] 
    [Display(Name="Ürün Var Mı?")] 
    public bool IsAvailable { get; set; } 
    [Required] 
    [Display(Name="Kategori")] 
    public Category Category { get; set; } 
    [Display(Name="Resim")] 
    public Image Image { get; set; } 
    [Required] 
    public DateTime CreatedOn { get; set; } 
    public DateTime ChangedOn { get; set; } 
    [Required] 
    public UserProfile CreatedBy { get; set; } 
    public UserProfile ChangedBy { get; set; } 

    public IEnumerable<SelectListItem> Categories 
    { 
     get 
     { 
      return new OnlineShoppingContext().Categories.OrderBy(c=>c.Name).ToList() 
      .Select(e => new SelectListItem { Text = e.Name, Value = e.Id.ToString() }); 
     } 
    } 
} 


[Table("Category")] 
public class Category 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } 
    [Required] 
    [Display(Name = "Kategori Adı")] 
    public string Name { get; set; } 
    [Display(Name = "Açıklama")] 
    public string Description { get; set; } 
    [Display(Name = "Resim")] 
    public Image Image { get; set; } 
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)] 
    public DateTime CreatedOn { get; set; } 
    public DateTime ChangedOn { get; set; } 
    public UserProfile CreatedBy { get; set; } 
    public UserProfile ChangedBy { get; set; } 
    public List<Product> Products { get; set; } 
} 

我的類別控制器

[Authorize(Roles = "Admin")] 
public class CategoryController : Controller 
{ 
    private OnlineShoppingContext db = new OnlineShoppingContext(); 

    // 
    // GET: /Category/ 

    public ActionResult Index() 
    { 
     return View(db.Categories.ToList()); 
    } 

    // 
    // GET: /Category/Details/5 

    public ActionResult Details(int id = 0) 
    { 
     Category category = db.Categories.Find(id); 
     if (category == null) 
     { 
      return HttpNotFound(); 
     } 
     return View(category); 
    } 

    // 
    // GET: /Category/Create 

    public ActionResult Create() 
    { 
     return View(); 
    } 

    // 
    // POST: /Category/Create 

    [HttpPost] 
    public ActionResult Create(Category category, HttpPostedFileBase file) 
    { 
     if (ModelState.IsValid) 
     { 
      if (file != null) 
      { 
       string pic = Guid.NewGuid().ToString(); 
       string path = Path.Combine(Server.MapPath("~/Content/images/"), pic + Path.GetExtension(file.FileName)); 
       file.SaveAs(path); 
       Image i = new Image(); 
       i.Path = path; 
       i.CreatedBy = db.UserProfiles.Where(u => u.UserId == WebSecurity.CurrentUserId).FirstOrDefault(); 
       category.Image = i; 
      } 
      category.CreatedBy = db.UserProfiles.Where(u => u.UserId == WebSecurity.CurrentUserId).FirstOrDefault(); 
      db.Categories.Add(category); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(category); 
    } 

    // 
    // GET: /Category/Edit/5 

    public ActionResult Edit(int id = 0) 
    { 
     Category category = db.Categories.Find(id); 
     if (category == null) 
     { 
      return HttpNotFound(); 
     } 
     return View(category); 
    } 

    // 
    // POST: /Category/Edit/5 

    [HttpPost] 
    public ActionResult Edit(Category category) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Entry(category).State = EntityState.Modified; 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     return View(category); 
    } 

    // 
    // GET: /Category/Delete/5 

    public ActionResult Delete(int id = 0) 
    { 
     Category category = db.Categories.Find(id); 
     if (category == null) 
     { 
      return HttpNotFound(); 
     } 
     return View(category); 
    } 

    // 
    // POST: /Category/Delete/5 

    [HttpPost, ActionName("Delete")] 
    public ActionResult DeleteConfirmed(int id) 
    { 
     Category category = db.Categories.Find(id); 
     db.Categories.Remove(category); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 

    protected override void Dispose(bool disposing) 
    { 
     db.Dispose(); 
     base.Dispose(disposing); 
    } 
} 

create.cshtml

@model OnlineShopping.Models.Product 

@{ 
    var db = new OnlineShopping.Models.OnlineShoppingContext(); 
    ViewBag.Title = "Create"; 
} 

<h2>Create</h2> 

@using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>Product</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Category) 
     </div> 
     <div class="editor-field"> 
      // Error Model is null 
      @Html.DropDownListFor(model => model.Category, new SelectList(Model.Categories, "Value", "Text")) 
      @Html.ValidationMessageFor(model => model.Category) 
     </div> 
     <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.Price) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Price) 
      @Html.ValidationMessageFor(model => model.Price) 
     </div> 

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

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

     <div class="editor-label"> 
      @Html.LabelFor(model => model.IsAvailable) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.IsAvailable) 
      @Html.ValidationMessageFor(model => model.IsAvailable) 
     </div> 
     <div class="editor-field"> 
      <input type="file" name="file" id="file" /> 
     </div> 
     <p> 
      <input type="submit" value="@Translations.Common.Create" /> 
     </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink(Translations.Common.BackToList, "Index") 
</div> 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 

在create.cshtml頁面我得到這個錯誤

異常詳細信息:系統。 NullReferenceException:未將對象引用設置爲對象的實例。 Line 19: Line 20: Line 21:@ Html.DropDownListFor(model => model.Category,new SelectList(Model.Categories,「Value」,「Text」)) Line 22:@ Html.ValidationMessageFor(model => model.Category) Line 23:

回答

0

在GET你的Model爲空,所以Model.Categories崩潰。請嘗試以下操作:

// 
// GET: /Category/Create 
public ActionResult Create() 
{ 
    var model = new OnlineShopping.Models.Product(); 
    return View(model); 
} 
+0

我收到此錯誤「值'1'無效。」並且ModelState.IsValid是false。我怎樣才能糾正這個錯誤? – verdery

0

你創建視圖希望你能在一個模型通過,那麼在您看來,它會尋找模型的產生下拉列表中爲你的價值。由於您尚未傳入模型,因此您會收到該對象空引用異常。

此外,當您傳入模型時,請確保它包含您需要填充下拉列表的所有數據。