【问题标题】:What Am I missing Here? (.NET, Razor,MVC)我在这里想念什么? (.NET、Razor、MVC)
【发布时间】:2017-06-10 03:30:11
【问题描述】:

我的主视图模型中有一个部分视图模型 我需要使用 Dictionary 方法为下拉列表状态模型返回 Byte

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

部分视图模型:

@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 中出现错误并出现异常 "输入字符串的格式不正确。"

【问题讨论】:

  • MVC 中的视图模型?真的吗?
  • 你错过了一个问题。
  • 你的问题到底是什么?
  • @JeremyWeir 我在 DropDownlistFor 中有一个错误,异常“输入字符串的格式不正确。”
  • @S.Serp 我在 DropDownlistFor 中有一个错误,出现异常“输入字符串的格式不正确。”

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


【解决方案1】:

下面一行有问题-

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

根据字典 x.Value 是一个字符串值。可以是字符串,但不能转换为有效数字。这就是为什么它不能转换为字节并抛出 FormatException 的原因。

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

解决方案是如下更改代码。

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

【讨论】:

  • 那毫无意义——只需删除那行代码。使用DropDownListFor() 方法时,Selected 属性被完全忽略
【解决方案2】:

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

【讨论】:

  • 不知道怎么回事!但它实际上有效!谢谢!
猜你喜欢
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
相关资源
最近更新 更多