0

我有这个模型,它有一个用于联系信息的字典:

public class UserInfo
{
    public int UserId { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    public Dictionary<ContactType, AccountContactInfo> ContactInfo { get; set; }

    public UserInfo()
    {
        ContactInfo = new Dictionary<ContactType, AccountContactInfo>();
    }
}

ContactType 是一个枚举,例如 Shipping、Billing 等。AccountContactInfo 是一个简单的视图模型。纯字符串属性,仅此而已。

这是读取模型的视图的示例部分。此 UserInfo 对象位于主模型内部:

<div id="shipping-address" class="confirm-addresses">
    <h3>Shipping Address</h3>
    @Html.LabelFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].Street)
    @Html.TextBoxFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].Street)

    @Html.LabelFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].City)
    @Html.TextBoxFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].City)

    @Html.LabelFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].State)
    @Html.TextBoxFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].State, new { maxlength = 2})

    @Html.LabelFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].Zip)
    @Html.TextBoxFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].Zip, new { maxlength = 5})

    @Html.LabelFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].Phone1)
    @Html.TextBoxFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].Phone1, new { maxlength = 10})

    @Html.LabelFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].Phone2)
    @Html.TextBoxFor(m => m.UserInfo.ContactInfo[ContactType.Shipping].Phone2, new { maxlength = 10})

</div>

如果这个完全建立模型到页面,它显示得非常好。但是,当我将其发送回控制器时,它会崩溃并出现以下异常:

异常详细信息:System.InvalidCastException:指定的强制转换无效。

它似乎与字典有关,并且这是我最近为添加字典所做的更改,我确定就是这样。如果有帮助,这里是堆栈跟踪:http: //pastebin.com/8vyPWiFn

我在控制器操作处设置了断点,但调试器从未到达这一点,所以我假设它在反序列化过程中的某个时刻中断?我不明白为什么这在输出页面时有效,但在返回控制器时无效。我发送的信息与发出的信息相同。

4

1 回答 1

0

是的,绑定字典有点棘手,您只需要提供正确的元素名称,例如:

@Html.Hidden("ContactInfo[0].Key", ContactType.Technical)
@Html.TextBox("ContactInfo[0].Value.Street", "Some street")

@Html.Hidden("ContactInfo[1].Key", ContactType.Billing)
@Html.TextBox("ContactInfo[1].Value.Street", "Some billing address")

您可能还会发现这篇文章很有帮助。

于 2013-08-04T05:07:10.523 回答