2013-04-04 110 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