自定义模型活页夹asp.net核心以绑定字典

时间:2019-07-03 14:50:31

标签: c# asp.net-core asp.net-core-mvc

我有以下代码来生成视图。这些字段应该从数据库中获取以生成html元素。字段类型可以是字符串,布尔值和数组。在发布数据时,如何将数据恢复为各自的类型?可以使用自定义模型绑定(IModelBinder)完成此操作。我一直在寻找示例,但找不到一个。

控制器:

public IActionResult Test()
        {
            var model = new Dictionary<string, object>
                {{"first", "firstValue"}, {"second", "secondValue"}, {"third", new[] {"arjun", "khadka"}}};
            //var view = new MyModel {MyDict = model};
            return View(model);
        }

        [HttpPost]
        public IActionResult Test(Dictionary<string, object> mydict)
        {
            var model = new Dictionary<string, object>();
            return View(model);
        }

查看:

@model Dictionary<string, object>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Test</title>
</head>
<body>
    <form method="post">
        @foreach (KeyValuePair<string, object> item in Model)
        {
            @if (item.Value is Array array)
            {<select multiple="multiple">
                    @foreach (var neitem in array)
                    {
                        <option value="@neitem">neitem</option>
                    }
                </select>
            }
            else
            {
                <input name="@item.Key" value="@item.Value" />
            }

        }
        <button type="submit"> save</button>
    </form>
</body>
</html>

页面:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

您不需要自定义模型活页夹。您只需要正确生成字段名称即可。

@foreach (var item in Model)
{
    if (item.Value is Array array)
    {
        <select asp-for="@Model[item.Key]" multiple="multiple">
            @foreach (var neitem in array)
            {
                <option value="@neitem">neitem</option>
            }
        </select>
    }
    else
    {
        <input asp-for="@Model[item.Key]" />
    }
}