2017-01-25 7 views
-1

は、私は私のメインのViewModel からの部分的なビューモデルを持っていると私は辞書の方法でドロップダウンリストのステータスモデルのバイトを返す必要がここで私は何が欠けていますか? (.NET、カミソリ、MVC)

public static class ListStatus 
{ 
    public static Byte Rejected = 0; 
    public static Byte Pending = 1; 
    public static Byte Reviewed = 2; 
    public static Byte Accepted = 3; 
} 

部分のViewModel:

@model byte 
@{ 
    Layout = null; 
    CategoryBusiness Business = new CategoryBusiness(); 
    object attr = this.ViewBag.attr ?? new { @class = "form-control" }; 
    RouteValueDictionary attrDictionary = (attr as RouteValueDictionary) ?? new RouteValueDictionary(attr); 
    attrDictionary["class"] = "required form-control"; 

    Dictionary<int, string> statuses = new Dictionary<int, string>(); 
    statuses.Add(Category.ListStatus.Rejected, "Rejected"); 
    statuses.Add(Category.ListStatus.Pending, "Pending"); 
    statuses.Add(Category.ListStatus.Reviewed, "Reviewed"); 
    statuses.Add(Category.ListStatus.Accepted, "Accepted"); 

    <div class="form-group"> 
     @Html.LabelFor(model => model, new { @class = "col-sm-2 control-label text-right" }) 
    <div class="col-sm-10 editor-field"> 
    @Html.DropDownListFor(model => model, statuses.Select(x => new SelectListItem 
    { 
     Text = x.Value, 
     Value = x.Key.ToString(), 
     Selected = Convert.ToByte(x.Value) == Model 
    })) 
    @if (ViewData.ModelState.ContainsKey(Html.NameForModel().ToString()) && ViewData.ModelState[Html.NameForModel().ToString()].Errors.Count > 0) 
    { 
     @Html.Raw(Html.ValidationMessageFor(model => model, null, htmlAttributes: new { @class = "error" }).ToHtmlString().Replace("span", "label")) 
    } 
</div> 
</div> 

DropDownlistForでエラーが発生しました "入力文字列が正しい形式ではありませんでした。"

+0

MVCのViewModel?本当に ? – lukai

+1

質問がありません。 – JeremyWeir

+0

あなたの問題は何ですか? –

答えて

1

次の行は、辞書x.Value当たりようproblem-

Selected = Convert.ToByte(x.Value) == Model 

を持つ文字列値です。文字列にするのは問題ありませんが、有効な数字に変換することはできません。そのため、Byteに変換できず、FormatExceptionがスローされます。

あなたは解決策には、次のようにコードを変更することですhttps://msdn.microsoft.com/en-us/library/c7xhf79k(v=vs.110).aspx

スルーに行くことができConvert.ToByteについての詳細を知っています。

Selected = Convert.ToByte(x.Key) == Model 
+0

それは無意味です - そのコード行を削除するだけです。 'Selected'プロパティは、' DropDownListFor() 'メソッドを使用すると完全に無視されます –

0

Selected = Convert.ToByte(x.Value) == Modelは実際にSelected = Convert.ToByte(x.Key.ToString()) == Modelである必要がありますか?

+0

何が起こっているのか分かりません!しかし、それは実際に動作します!ありがとう! – Richard

関連する問題