2013-04-04 107 views
1

我有一個奇怪的問題,MVC下拉選擇的值沒有預先選擇頁面加載。Dropdownlist沒有選擇預選值-mvc3

我的模型是:

public class DocumentTypesViewModel 
    { 
     [Required(ErrorMessage = "DocumentType is required")] 
     public int OHDocumentTypeId { get; set; } 
     public string OHDocumentTypeDescription { get; set; } 
    } 



public class ClientAdvancedSearchViewModel 
    { 
     [Display(Name = "Name")] 
     public string Name { get; set; } 
     [Display(Name = "DocumentType")] 
     public string DocumentTypeId { get; set; } 
     public IEnumerable<SelectListItem> DocumentTypes { get; set; } 
    } 

在我的控制器,我填充ClientAdvancedSearchViewModel這樣

[HttpGet] 
    public ActionResult ClientAdvancedSearch() 
    { 

     ClientAdvancedSearchViewModel clientAdvancedSearchViewModel = iClientReferralRecordsRepository.GetDocumentMetadata(); 
     //DocumentTypes Dropdown 
     var ddlDocumentTypes = iDocumentTypeRepository.GetDocumentTypes(); 
     clientAdvancedSearchViewModel.DocumentTypes = new SelectList(ddlDocumentTypes, "OHDocumentTypeId", "OHDocumentTypeDescription",clientAdvancedSearchViewModel.DocumentTypeId); 
     return View(clientAdvancedSearchViewModel); 
    } 

終於在查看:

<td> 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.DocumentTypes) 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(x => x.DocumentTypeId, Model.DocumentTypes, "Please Select", new { @id = "ddlDocumentType" }) 
    </div> 
    </td> 

相信的名稱下拉是相同的是x => x.DocumentTypeId,因爲我認爲,我的價值不是預選反恐執行局。

這是ViewSource用於生成的HTML的下拉

<select id="ddlDocumentType" name="DocumentTypeId"> 
<option value="">Please Select</option> 
<option value="20">records</option> 
<option value="21"> record1</option> 

..

如何重命名我的下拉列表名稱或怎樣才能解決我的問題?

謝謝

更新:增加了遺漏線

ClientAdvancedSearchViewModel clientAdvancedSearchViewModel = iClientReferralRecordsRepository.GetDocumentMetadata(); 

回答

1

您對您的視圖代碼是恰到好處。您忘記設置DocumentTypeId的值。這是你的代碼爲您發佈:

[HttpGet] 
public ActionResult ClientAdvancedSearch() 
{ 
    //DocumentTypes Dropdown 
    var ddlDocumentTypes = iDocumentTypeRepository.GetDocumentTypes(); 
    clientAdvancedSearchViewModel.DocumentTypes = new SelectList(ddlDocumentTypes, "OHDocumentTypeId", "OHDocumentTypeDescription",clientAdvancedSearchViewModel.DocumentTypeId); 
    return View(clientAdvancedSearchViewModel); 
} 

你錯過了這一點:

clientAdvancedSearchViewModel.DocumentTypeId = some_value; 

另外,你打算有DocumentTypeIdint,而不是string

UPDATE: 您還可以檢查你這樣設置ID:

@Html.DropDownListFor(x => x.DocumentTypeId, new SelectList(Model.DocumentTypes, "Id", "Value", Model.DocumentTypeId), new { @id = "ddlDocumentType" }) 

通知我使用過載與new SelectList。我不記得所有的重載,我一直這樣做,所以你可以檢查我們的其他過載,適合你的需要。

+0

很好的代碼跟蹤 – 2013-04-04 13:51:16

+0

我正在設置它,但刪除了粘貼在SO中的行。 clientAdvancedSearchViewModel = iClientReferralRecordsRepository.GetDocumentMetadata(); – 2013-04-04 13:51:44

+0

請張貼所有相關代碼,然後供我們參閱。但是看到我更新的答案。 – 2013-04-04 13:56:54