属性是通过Controller在ViewModel中设置的,但是当在View中显示它时它是空的?

时间:2011-08-09 21:21:15

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

我有以下ViewModel

    public class ShowQuestionsViewModel
{
    public String CategoryName { get; set; }
    public String CategoryNumber { get; set; }

    public List<QuestionViewModel> QuestionsInCategory { get; set; }

    public ShowQuestionsViewModel()
    {
        QuestionsInCategory = new List<QuestionViewModel>();
    }
}

在我的控制器中,我设置了这样的属性(片段):

ShowQuestionsViewModel sqvmsub = new ShowQuestionsViewModel();

var questionsSub = db.Question.Where(y => y.category_id == sub.category_id).ToList();

if (questionsSub != null)
{
   sqvmsub.CategoryName = sub.category_name;
   sqvm.CategoryNumber = sub.prefix;
   .....
}

当我尝试在我的视图中显示属性时,CategoryNumber属性为空,即使它在控制器中设置(我通过调试检查)..:

@foreach (var item in Model)
{
    if (item.QuestionsInCategory.Count != 0)
    {
    <h3>@Html.LabelFor(y => item.CategoryName, item.CategoryName)</h3>
    <h3>@Html.LabelFor(y => item.CategoryNumber, item.CategoryNumber)</h3>

@ Html.LabelFor(y =&gt; item.CategoryNumber,item.CategoryNumber)

仅显示文本“CategoryNumber”

如果我尝试更改我的控制器:

sqvmsub.CategoryName = sub.prefix;

它显示它应该是什么,这意味着sub.prefix没有任何问题,但在ShowQuestionsViewModel中有CategoryNumber ..

有没有人知道出了什么问题?

1 个答案:

答案 0 :(得分:0)

我显然没有正确设置属性。我改成了:

ShowQuestionsViewModel sqvm = null;

var questionsMain = db.Question.Where(y => y.category_id == s.category_id).ToList();

if (questionsMain != null)
   {
      sqvm = new ShowQuestionsViewModel() { CategoryNumber = s.prefix, 
                                            CategoryName = s.category_name };
.....
}

它现在有效。谢谢你的帮助。