[英]Custom Model binder asp.net core to bind dictionary
I have following code to generate view.我有以下代码来生成视图。 Those fields are supposed to be fetched from database to generate html elements.
这些字段应该从数据库中获取以生成 html 元素。 Field type could be string, bool and Array.
字段类型可以是字符串、布尔值和数组。 On posting data how can I get back data to respective types?
在发布数据时,如何将数据恢复到相应类型? Can this be done using custom model binding ( IModelBinder ).
这可以使用自定义模型绑定 ( IModelBinder ) 来完成。 I have been looking example but could not find one.
我一直在寻找示例,但找不到一个。
Controller:控制器:
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);
}
View:看法:
@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>
Page:页:
You don't need a custom model binder.您不需要自定义模型绑定器。 You just need to generate the field names properly.
您只需要正确生成字段名称。
@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]" />
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.