我在这里错过了什么? (.NET,Razor,MVC)

时间:2017-01-25 04:21:20

标签: c# .net razor asp.net-mvc-5

我的主ViewModel中有一个部分ViewModel 我需要使用Dictionary方法

返回Byte for dropdownlist status model
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中遇到异常错误 “输入字符串的格式不正确。”

2 个答案:

答案 0 :(得分:1)

以下行有问题 -

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

根据字典x.Value是一个字符串值。它可以成为字符串,但它不能转换为有效数字。这就是它无法转换为Byte和FormatException的原因。

要了解有关Convert.ToByte的更多信息,您可以通过https://msdn.microsoft.com/en-us/library/c7xhf79k(v=vs.110).aspx

解决方案是将代码更改为以下内容。

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

答案 1 :(得分:0)

不应该Selected = Convert.ToByte(x.Value) == Model实际上是Selected = Convert.ToByte(x.Key.ToString()) == Model吗?