首页 文章

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

提问于
浏览
0

我查看了大多数处理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:using System;使用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 => model.GarageId,Model.LkupGarageTypes)@ Html.ValidationMessageFor(model => model.GarageType)

1 回答

  • 0

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

    尝试将视图上的模型更改为 MvcPropertyManagement.Models.ViewModels.PropertyViewModel

    @model MvcPropertyManagement.Models.ViewModels.PropertyViewModel
    

    UPDATE: 属性类,用于模型:

    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);
    }
    

相关问题