2011-10-30 58 views
1

一種製品視圖模型入門從DropDownList中在asp.net MVC 3

public class ArticleViewModel : ViewModelBase 
    { 

     [Required(ErrorMessage = "Required")] 
     public string Title { get; set; } 
     [Required(ErrorMessage = "Choose the language")] 
     public BELocale Locale { get; set; } 
} 

public class BELocale : BEEntityBase 
    { 

     public string OriginalName { get; set; } 
     public string FriendlyName { get; set; } 
     public string TwoLetterISOName { get; set; } 
    } 

視圖 「AddLocaleForArticle」

@model Models.ArticleViewModel 

@using (Html.BeginForm("VefifyAddingLocaleForArticle", "Administration")) 
{ 

@Html.TextBoxFor(m => m.Title, new { disabled = "disabled" }) 
@Html.DropDownListFor(m => m.Locale, 
        new SelectList(ViewBag.AvalaibleLocales, "ID", "OriginalName"), "Select a language" 
       ) 
    @Html.ValidationMessageFor(m => m.Locale) 
    <input type="submit" value="Save" />   
} 

一個動作

public ActionResult VefifyAddingLocaleForPhoto(ArticleViewModel article) 
     { 
      //article.Locale == null for some reason. 
      //but article.Title isn't null, it contains the data 
      return RedirectToAction("AddingLocaleForPhotoSuccess", "adminka"); 
     } 

爲什麼article.Locale選定值是否等於null以及如何修復它?

+0

檢查HTML中的下拉列表的名稱 –

+0

HTML中的名稱爲「Locale」。 – Alexandre

+0

「ID」似乎不存在於您的視圖模型中 – Tassadaque

回答

2

當表單提交的下拉列表只有選定的值發送到控制器。因此,您不能指望它使用下拉列表填充整個複雜對象,例如BELocale。最好的辦法是填充其ID屬性並使用此ID從數據存儲中獲取剩餘的對象。

所以,你將不得不修改您的下拉列表幫手,這樣勢必語言環境作爲第一個參數的id屬性:

@Html.DropDownListFor(
    m => m.Locale.ID, 
    new SelectList(ViewBag.AvalaibleLocales, "ID", "OriginalName"), 
    "Select a language" 
) 

現在相應的控制器的動作裏面,你會得到ID:

public ActionResult VefifyAddingLocaleForPhoto(ArticleViewModel article) 
{ 
    // article.Locale.ID will contain the selected locale id 
    // so you can use this information to fetch the corresponding BELocale object 
    ... 
} 
+0

'@ Html.DropDownList(「ddlCountry」,new SelectList(ViewBag.lstCountry,「CountryID」,「CountryName」))''。在選擇一個特定的國家時,我想將'CountryID'傳遞給** countroller **。如何使用* jQuery *來完成? **注意:**我**不是**使用*強類型查看* – barnes

0

你可以在你的視圖模型

public List<KeyValuePair<int, String>> locale 
     { 
      get 
      { 
       return _localerepo.Findlocals().Select(x => new KeyValuePair<int, string>(x.ID, x.OriginalName)).ToList(); 
      } 
     } 

填補下拉像這樣在你看來使用本

<%:Html.DropDownListFor(x => x.ID, new SelectList(Model.locale, "key", "value"), "--Select locale--")%> 
       <%= Html.ValidationMessageFor(model => model.ID)%>