具有键“CityId”的ViewData项的类型为“System.Int32”,但必须是“IEnumerable <selectlistitem>”类型</selectlistitem>

时间:2014-09-02 11:01:28

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

 `       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>

我用于创建页面的相同代码及其在那里工作但不在编辑页面上。我根据你改变了我的代码,但仍然没有提交数据。虽然有时间可以。但

2 个答案:

答案 0 :(得分: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)

然后您可以将ViewBag.City用于DropDownList。

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

答案 1 :(得分:0)

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