2014-03-19 127 views
0

我已經搜索了不少頁面等,找不到任何東西來真正幫助我。我有一個加載的視圖模型,然後我需要從選定的「DocumentTypeList」中獲取ID,以便將其分配給Document對象上的DocumentTypeId。如何從@ Html.DropDownListFor獲取所選項目

我必須將「DocumentTypeList」放在我的Document類上,還是保持它在視圖模型中的位置?

這是我的視圖模型。

#region Properties 
    public Document Document { get; set; } 

    public List<CultureInfo> AvaialableLocales { get; set; } 

    public IEnumerable<DocumentType> DocumentTypeList {get; set;} 
    #endregion 

    #region Constructor 
    public FileUploadViewModel() 
    { 
     Document = new Document(); 

     AvaialableLocales = GTSSupportedLocales.Locales; 
    } 
    #endregion 

這是我的觀點是,在網頁

@Html.DropDownListFor(x => x.DocumentTypeList, new SelectList(Model.DocumentTypeList, "Code", "Description"), "-- Please Select --") 

在視圖模型,這裏是我打電話

[HttpPost] 
    public ActionResult SaveFile(FileUploadViewModel Doc) 
    { 
     if (Request.Files.Count > 0) 
     { 
      var file = Request.Files[0]; 

      if (file != null && file.ContentLength > 0) 
      { 
       using (Stream inputStream = file.InputStream) 
       { 
        MemoryStream memoryStream = inputStream as MemoryStream; 
        if (memoryStream == null) 
        { 
         memoryStream = new MemoryStream(); 
         inputStream.CopyTo(memoryStream); 
        } 
        Doc.Document.UploadedFile = memoryStream.ToArray(); 
       } 
      } 
     }   

     return Content("File is being uploaded"); 
    } 

UPDATE

我已經找到了行動解決方案的工作。感謝您的所有意見。

@Html.DropDownListFor(n => n.Document.DocumentTypeId, Model.DocumentTypeList.Select(option => new SelectListItem() 
       { 
        Text = option.Description, 
        Value = option.ID.ToString(), 
        Selected = (!Model.Document.DocumentTypeId.IsNull() && (Model.Document.DocumentTypeId == option.ID)) 
       })) 
+0

你想在SaveFile中下拉選定的值操作? –

+0

@ JcMey3r你解決了這個問題嗎? –

回答

0

在ViewModel中創建另一個獲取selectedValue的屬性。

public DocumentType SelectedDocumentType {get; set;} 

更改您的DropDownList像這樣

Html.DropDownListFor(n => n.SelectedDocumentType, new SelectList(DocumentTypeList, "Code", "Description")) 

的的SelectedValue可以使用SelectedDocumentType屬性來訪問。

0

由於@DarinDimitrov回答了here,在ASP.NET MVC中,助手DropDownListFor無法確定當您使用lambda表達式作爲第一個參數時所選項目,因爲它表示具有集合的複雜屬性。

這是一個限制,但你應該能夠使用助手,設置在您的視圖模型一個簡單的屬性,因爲作爲幫手第一個參數傳遞lambda表達式,以這樣的方式

public DocumentType MySelectedDocumentType {get; set;} 

然後你的助手聲明將是這樣的:

@Html.DropDownListFor(x => x.MySelectedDocumentType, new SelectList(Model.DocumentTypeList, "Code", "Description"), "-- Please Select --") 

我必須把「DocumentTypeList」我的文檔類或保持 它是在視圖模型?

出於上述原因,您不應該在助手中使用泛型集合來獲取選定的項目。

相關問題