【问题标题】:MVC 4 Binding to a dictionaryMVC 4 绑定到字典
【发布时间】:2013-07-25 12:56:58
【问题描述】:

我在 Internet 上四处查看,但似乎没有一个解决方案适合我。

我有以下视图模型:

public class ConfigsViewModel
{
    // iOS Dictionary
    public Dictionary<string, object> IosDictionary { get; set; }   

    // Android Dictionary
    public Dictionary<string, object> AndroidDictionary { get; set; } 
}

这些字典中的值要么是布尔值,要么是字符串。我想显示一个类似于编辑视图的表格,并且我想绑定这些字典。我的观点是这样的:

@model MobileRebrandingTool.Models.ViewModels.ConfigsViewModel

<div>
    @using (Html.BeginForm("SaveAppConfig", "Project", "POST"))
    {
        <table class="config-table">
            <tr>
                <th></th>
                <th>iOS</th>
                <th>Android</th>
            </tr>
            @foreach (var kvp in Model.IosDictionary)
            {
                <tr>
                    <td>
                        @kvp.Key
                    </td>
                    <td>
                        @Html.EditorFor(model => model.IosDictionary[kvp.Key])
                    </td>
                    <td>
                        @if (Model.AndroidDictionary.ContainsKey(kvp.Key))
                        {
                            @Html.EditorFor(model => model.AndroidDictionary[kvp.Key])
                        }
                    </td>
                </tr>
            }
        </table>
        <input type="submit" value="Save"/>    
    }
</div>

问题在于,在 SaveAppConfig 操作中,当我检查模型时,而不是字符串作为字典中键的值,该值是一个字符串的数组(文本输入中的值)。 在字典中,我有布尔值和字符串作为值,所以我不能使用 TextBoxFor。 有没有更好的方法来绑定字典?我应该写一个自定义活页夹吗?如果是这样,它应该是什么样子?

谢谢,

Cosmin

【问题讨论】:

    标签: asp.net-mvc-4 dictionary bind editorformodel


    【解决方案1】:

    由于您在 foreach 中,因此您需要稍微不同地提取值

    @foreach(var kvp in Model.IosDictionary){
        @Html.EditorFor(model => model.IosDictionary[kvp.Key])
    }
    

    应该是这样的

    @foreach(var kvp in Model.IosDictionary){
        @Html.EditorFor(model => kvp.Value)
    }
    

    我不是 100% 确定你可以做 kvp.Value。查找遍历字典并找到这个What is the best way to iterate over a Dictionary in C#?

    【讨论】:

    • Dictionary 实现了IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;,因此实际上您可以对其进行迭代。此外,这不起作用(好吧,它似乎会起作用,直到您发布)。
    猜你喜欢
    • 2011-07-08
    • 2014-04-10
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多