MVC 3 DropDownList视图/模型/控制器的语法

时间:2012-04-17 06:31:52

标签: asp.net-mvc

我查看了大多数处理MVC的博客文章以及如何使用DropDownList但收效甚微。

我试图在此链接模仿帖子,但显然不适合我:Drop-Down Menu Causing Invalid Model State. ASP.NET MVC 3

目标是为用户提供一个下拉列表,以便在HTTP GET创建视图中选择家庭车库所拥有的汽车数量。

我目前收到的错误是:

编译器错误消息:CS1061:'MvcPropertyManagement.Models.Property'不包含'GarageId'的定义,并且没有扩展方法'GarageId'接受类型'MvcPropertyManagement.Models.Property'的第一个参数可以找到(是你错过了使用指令或程序集引用?)

第84行: 第85行: 第86行:@ Html.DropDownListFor(model => model.GarageId,Model.LkupGarageTypes) 第87行:@ Html.ValidationMessageFor(model => model.GarageType) 第88行:

我的模特:     使用系统;     使用System.Collections.Generic;     使用System.Linq;     使用System.Web;     使用System.ComponentModel.DataAnnotations;     使用System.Web.Mvc;     使用MvcPropertyManagement.Models;     使用MvcPropertyManagement.Models.ViewModels;

namespace MvcPropertyManagement.Models
{
    public class Property
    {
        public bool Garage { get; set; }

        [Display(Name="Garage Capacity")]
        public string GarageType { get; set; }
}

控制器:     使用系统;     使用System.Data;     使用System.Collections.Generic;     使用System.Data.Entity;     使用System.Linq;     使用System.Web;     使用System.Web.Mvc;     使用MvcPropertyManagement.Models;     使用MvcPropertyManagement.Models.ViewModels;

public ActionResult Create()
{
    PropertyViewModel viewModel = new PropertyViewModel();
    viewModel.LkUpGarageType = new SelectList(db.LkUpGarageTypes, "GarageTypeID",         "LkUpGarageType"); 
    return View(viewModel);
} 

PropertyViewModel:     使用系统;     使用System.Collections.Generic;     使用System.Linq;     使用System.Web;     使用System.Web.Mvc;     使用MvcPropertyManagement.Models;

namespace MvcPropertyManagement.Models.ViewModels
{
    public class PropertyViewModel
    {
        public int? GarageId { get; set; }
        public IEnumerable<SelectListItem> LkUpGarageType { get; set; }        
    }
}

创建视图:              @ Html.DropDownListFor(model =&gt; model.GarageId,Model.LkupGarageTypes)         @ Html.ValidationMessageFor(model =&gt; model.GarageType)     

1 个答案:

答案 0 :(得分:0)

好像您使用的是MvcPropertyManagement.Models.Property作为模型,而不是使用GarageId的MvcPropertyManagement.Models.ViewModels.PropertyViewModel

尝试使用以下内容将模型更改为MvcPropertyManagement.Models.ViewModels.PropertyViewModel

@model MvcPropertyManagement.Models.ViewModels.PropertyViewModel

<强>更新 属性类,用于模型:

public class Property
{
  public bool Garage { get; set; }

  [Display(Name="Garage Capacity")]
  public string GarageType { get; set; }

  public int? GarageId { get; set; }

  public IEnumerable<SelectListItem> LkUpGarageType { get; set; } 
}

创建动作:

public ActionResult Create()
{
  Property viewModel = new Property();
  viewModel.LkUpGarageType = new SelectList(db.LkUpGarageTypes, "GarageTypeID",         "LkUpGarageType"); 
  return View(viewModel);
} 
相关问题