如何使用强类型数据模型循环遍历viewBag

时间:2015-07-30 15:12:59

标签: c# linq razor asp.net-mvc-5 viewbag

我有ViewBag的强类型模型数据,我需要在剃刀中循环模型数据,我该怎么做。

Razor(需要帮助)

@foreach (var item in ViewBag.PropertyRentingPrise)
{
    //@Html.DisplayFor(item.PropertyRentingPrise)
      ???????????????????????????????????????
}

控制器

 ViewBag.PropertyRentingPrise = _propertyManagementServices.GetAllPropertyRentingPrice();

返回记录列表

的函数
 public List<PropertyRentingPrice> GetAllPropertyRentingPrice()
    {
        try
        {
            using (var _uow = new PropertiesManagement_UnitOfWork())
            {
                var _records = (from _propertyTypeList in _uow.PropertyRentingPrice_Repository.GetAll()
                                select _propertyTypeList).ToList();

                return _records;
            }


        }
        catch { return null; }
    }

模型类

 public class PropertyRentingPrice
{
     public PropertyRentingPrice() { }


     [Key]
     [Column(Order = 0)]
     [Display(Name = "Property Renting ID")]
     public int RentingID { get; set; }

     [Key][Column(Order=1)]
     [Display(Name = "Housing Organization ID")]
     [Required(ErrorMessage = "Require Housing Organization ID")]
     public int HousingOrganizationID { get; set; }

     [Key]
     [Column(Order = 2)]
     [Display(Name = "Property Type ID")]
     [Required(ErrorMessage = "Require Property Type ID")]
     public int PropertyTypeID { get; set; }

     [Display(Name = "Cost Per Week")]
     [Required(ErrorMessage = "Require Cost Per Week Based on Property Type")]
     public decimal CostPerWeek { get; set; }

     [Display(Name = "Cost Per Month")]
     [Required(ErrorMessage = "Require Cost Per Month Based on Property Type")]
     public decimal CostPerMonth { get; set; }

     [Display(Name = "Currency")]
     [Required(ErrorMessage = "Require Currency In Which Property Been Advertised, Type £ for British Pound")]
     public string Currency { get; set; }

     [Display(Name = "Maximum Occupancy")]
     [Required(ErrorMessage = "Require Maximum Number Occupancy Based on Property Type")]
     public int MaximumOccupancy { get; set; }

     [Display(Name = "Bill Includes")]
     [Required(ErrorMessage = "Require Yes/No if Property Rent Includes Bills")]
     public bool Bill_Includes { get; set; }

     public HousingOrganization HousingOrganization { get; set; }
     public PropertyType PropertyType { get; set; }

}

1 个答案:

答案 0 :(得分:0)

您需要将ViewBag对象解析为PropertyRentingPrice的List。

试试这个:

@{
    var m = ViewBag.PropertyRentingPrice as List<PropertyRentingPrice>;
}

@foreach(var item in m)
{

}