【问题标题】:The ViewData item that has the key 'CityId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>' [duplicate]具有键“CityId”的 ViewData 项属于“System.Int32”类型,但必须属于“IEnumerable<SelectListItem>”类型 [重复]
【发布时间】:2014-09-02 11:01:28
【问题描述】:
 `       public ActionResult Edit(int id = 0)
    {
        property property = db.Properties.Find(id);

        try
        {
            ViewBag.City = new SelectList(db.Cities, "CityId", "City", property.CityId);
            ViewBag.Locality_Id = new SelectList(db.Areas, "Locality_Id", "Locality", property.Locality_Id);
            ViewBag.citylist = _data.getCity();
            ViewBag.typeproperty = _data.TypeProperty();
            ViewBag.Rooms = _data.RoomDetails();
            ViewBag.bath = _data.Bathroom();
            ViewBag.twowheel = _data.twowheeler();
            ViewBag.fourwheel = _data.fourwheeler();
            ViewBag.dir = _data.Direction();
            ViewBag.floor = _data.Flooring();
            ViewBag.water = _data.WaterSupplies();
            ViewBag.furnish = _data.Furnishes();
            ViewBag.Amenities = new SelectList(db.Amenities, "AmenitiesId", "Amenitie");
        }
        catch (Exception ex)
        {
           Console.Write( ex.InnerException.StackTrace.ToString());
        }



        if (property == null)
        {
            return HttpNotFound();
        }
        return View(property);
    }`    

 <div class="form-box-left">
                   <h5>* Select The City :</h5>
                 @Html.DropDownList("CityId", null, "Select City", new { @class = "text-box", Id = "City" })
                  @Html.ValidationMessageFor(model => model.CityId)
                   <h5>* Locality :</h5>

我用于创建页面的相同代码及其在该页面上的工作,但不在编辑页面上。我根据你更改了我的代码,但它仍然没有提交数据。有时间就好了。

【问题讨论】:

  • 我们可以看到编辑和创建操作方法的控制器代码吗?

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

以下代码是使用空 DropDownList 的示例:

@Html.DropDownList("CityId", Enumerable.Empty<SelectListItem>(), "Select City", new { @class = "text-box", Id = "City" })

要使用相关数据填充 DropDownList,您可以使用 ViewBag 发送数据。

例子:

首先,您需要将城市列表输入ViewBag.City

ViewBag.City = new SelectList(cityList, value, text, selectedCity)

然后你可以在 DropDownList 中使用ViewBag.City

@Html.DropDownList("CityId", ViewBag.City as SelectList, "Select City", new { @class = "text-box", Id = "City" })

【讨论】:

  • 这样它不会为编辑页面选择城市。它甚至没有选择城市列表。
  • 除了用城市列表填充它之外,我还希望选择一个特定城市。这样我只能获取城市列表。
  • @Smokingmonkey,选择的值将是属性CityId的值,所以如果你在你的模型中设置值CityId = 5并且你有一个值为5的SlectListItem,那么它将被选中。
【解决方案2】:

您将 null 作为 Html.DropDownList 的元素传递。在这种情况下,引擎会从“CityId”键下的 ViewData 字典中选择元素。我假设那里有一个 Int32 类型的对象(即 ViewData [“CityId”])。这是默认行为。

【讨论】:

  • 那么它对创建页面有什么作用呢?
猜你喜欢
  • 2018-07-24
  • 2016-03-25
  • 2016-03-21
  • 2014-11-13
  • 2023-03-12
  • 2013-01-19
相关资源
最近更新 更多