2011-07-08 47 views
6

我無法獲得一個選擇列表來綁定到我的ViewModel。如何將選擇列表與視圖模型綁定?

我有一個包含一個問題實體和字符串

public class QuestionViewModel 
{ 
    public Question Question { get; set; } 
    public string RefUrl { get; set; } 

    public QuestionViewModel() 
    { 
    } 

    public QuestionViewModel(Question question, string RefUrl) 
    { 
     this.Question = question; 
     this.RefUrl = RefUrl; 
    } 

    public QuestionViewModel(Question question) 
    { 
     this.Question = question; 
     this.RefUrl = ""; 
    } 
} 

這是控制器視圖模型:

public ActionResult Edit(int id) 
    { 
     Question question = db.Question.Single(q => q.question_id == id); 
     QuestionViewModel qvm = new QuestionViewModel(question); 
     ViewBag.category_id = new SelectList(db.Category, "category_id", "category_name", qvm.Question.category_id); 
     ViewBag.type_code = new SelectList(db.Question_Type, "type_code", "type_description", qvm.Question.type_code); 
     return View(qvm); 
    } 

,並在我看來,代碼如下所示:

​​

視圖沒有將Question實體的Question_Type設置爲選定的值,但是當我提交表單時,th e ValidationMessageFor觸發器

+0

Model.Question.Question_Type Model.Question.type_code是2個不同的屬性? 你有Question.type_code的驗證信息,但你正在設置Question_Type? –

回答

14

你有什麼是不是一個查看模型。這是一個混合類,您稱爲查看模型並且其中包含了您的域實體(Question)。這很糟糕,不要這樣做。

這是我會推薦你​​的。

public class QuestionViewModel 
{ 
    [DisplayName("Question_Type")] 
    public string SelectedQuestionType { get; set; } 

    public IEnumerable<SelectListItem> QuestionTypes { get; set; } 

    // didn't see where you are using this on your view 
    public string RefUrl { get; set; } 
} 

則有:通過設計將反映您觀的要求(從當前說明它是一個包含了一些問題類型,並允許用戶選擇從這個DDL一些問題類型下拉列表)一個真正的視圖模式啓動您的域控模型和視圖模型之間的控制器映射。當然,進一步的改進是使用AutoMapper,以避免在你的控制器操作的映射:

public ActionResult Edit(int id) 
{ 
    var question = db.Question.Single(q => q.question_id == id); 
    var qvm = new QuestionViewModel 
    { 
     // preselect a value 
     SelectedQuestionType = question.type_code, 
     QuestionTypes = db.Question_Type.Select(x => new SelectListItem 
     { 
      Value = x.type_code, 
      Text = x.type_description 
     }) 
    }; 
    return View(qvm); 
} 

然後:

<div class="editor-label"> 
    @Html.LabelFor(x => x.SelectedQuestionType) 
</div> 
<div class="editor-field"> 
    @Html.DropDownListFor(
     x => SelectedQuestionType, 
     new SelectList(Model.QuestionTypes, "Value", "Text") 
    ) 
    @Html.ValidationMessageFor(x => x.SelectedQuestionType) 
</div> 

而且最後再說一句:確保你已經擺脫了任何並且將視圖需要的任何東西放入視圖模型中。您已在控制器操作中顯示了一些類別,這些類別在您顯示的視圖片段中未實現。如果您需要它們,只需將它們放入您的視圖模型中,就像我們對問題類型所做的那樣。

+0

但我需要將問題實體發送到視圖,以便我可以編輯它?這樣你只發送包含Question_Type和ref_URL – Nanek

+1

@Nanek的QuestionViewModel,不需要發送任何Question實體到你的視圖。正如我所說的,您需要在視圖中編輯的所有屬性必須是視圖模型的一部分。然後,您的發佈操作將採用相同的視圖模型,並將其映射回域問題模型,該模型將發送到存儲庫進行編輯或任何需要的模型。 –

+0

@Darin,爲什麼QuestionTypes在發佈後爲null? Post方法會是什麼樣子? – mcass20

相關問題