MVC 4 Razor我无法在foreach中显示列表项

时间:2012-09-19 15:36:55

标签: razor asp.net-mvc-4

我想显示列表的内容,该列表是我的模型的属性,但呈现的HTML代码为空,这里是我的代码:

查看

@foreach (Namespace.Models.Criteria crit in Model.CriteriaListToSearch)
{
    <div class="selectedItem">@crit.CriteriaType : @crit.TextToSearch</div>
}

查看模型

public class Search
{
    public IEnumerable<EquipmentModel> Equipments;
    public IEnumerable<SparePartsModel> SpareParts;
    public List<Criteria> CriteriaListToSearch;

    public Search()
    {
        CriteriaListToSearch = new List<Criteria>();
    }

    #region Criteria

    private List<SelectListItem> _CriteriaList;                
    public List<SelectListItem> CriteriaList
    {
        get
        {
            if (_CriteriaList == null)
            {
                _CriteriaList = new List<SelectListItem>(4) 
                { 
                    new SelectListItem { Value = "", Text = "Select an option"},
                    new SelectListItem { Value = "1", Text = "Name/Number"},
                    new SelectListItem { Value = "2", Text = "Type"},
                    new SelectListItem { Value = "3", Text = "Description"}
                };
            }

            return _CriteriaList;
        }
    }

    [Display(Name = "Options")]
    [Required(ErrorMessage = "Please select an option.")]
    public string CriteriaSelected { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "The search field is required.")]
    [Display(Name = "Search")]
    [StringLength(100)]
    public string TextToSearch { get; set; }

    #endregion
}

public class Criteria
{
    public string CriteriaType;
    public string TextToSearch;
}

Model.CriteriaListToSearch是我的列表,有一个项目,我用断点检查。我尝试通过前缀标记来显示它,失败。

[HttpPost]
public ActionResult AddCriteria(Search model)
{ 
   if (model == null) model = new Search();
   Criteria crit = new Criteria();
   crit.CriteriaType = model.CriteriaSelected;
   crit.TextToSearch = model.TextToSearch;
   model.CriteriaListToSearch.Add(crit);
   return View("Index", model);
}

调试:

a busy cat http://i49.tinypic.com/smg9cm.jpg

还有其他办法吗?

2 个答案:

答案 0 :(得分:0)

如果列表中有项目且CriteriaTypeTextToSearch属性不为null或为空,那么这应该有效。还要确保没有隐藏div的CSS规则。您可以使用FireBug或Chrome Developer Toolbar检查您的DOM,并分析应用于生成的div的所有CSS规则。

答案 1 :(得分:0)

你的模特是什么样的? Razor可能正在调用ToString()来显示您的数据。