加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 模型绑定字典

发布时间:2020-12-15 08:19:33 所属栏目:百科 来源:网络整理
导读:我的控制器动作方法传递一个Dictionary string,double?到了视野.我认为我有以下几点: % foreach (var item in Model.Items) { %%: Html.Label(item.Key,item.Key)%%: Html.TextBox(item.Key,item.Value)%% } % 下面是我处理POST操作的action方法: [HttpPo
我的控制器动作方法传递一个Dictionary< string,double?>到了视野.我认为我有以下几点:
<% foreach (var item in Model.Items) { %>
<%: Html.Label(item.Key,item.Key)%>
<%: Html.TextBox(item.Key,item.Value)%>
<% } %>

下面是我处理POST操作的action方法:

[HttpPost]
public virtual ActionResult MyMethod(Dictionary<string,double?> items)
{
    // do stuff........
    return View();
}

当我在文本框中输入一些值并点击提交按钮时,POST操作方法没有收到任何项目?我究竟做错了什么?

解决方法

我建议你阅读 this blog post关于如何命名你的输入字段,以便你可以绑定到字典.因此,您需要为密钥添加一个额外的隐藏字段:
<input type="hidden" name="items[0].Key" value="key1" />
<input type="text" name="items[0].Value" value="15.4" />
<input type="hidden" name="items[1].Key" value="key2" />
<input type="text" name="items[1].Value" value="17.8" />

可以通过以下方式生成:

<% var index = 0; %>
<% foreach (var key in Model.Keys) { %>
    <%: Html.Hidden("items[" + index + "].Key",key) %>
    <%: Html.TextBox("items[" + index +"].Value",Model[key]) %>
    <% index++; %>
<% } %>

这就是说,我个人建议你不要在你的观点中使用词典.它们很难看,为了为模型绑定器生成专有名称,您需要编写丑陋的代码.我会使用视图模型.这是一个例子:

模型:

public class MyViewModel
{
    public string Key { get; set; }
    public double? Value { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new[]
        {
            new MyViewModel { Key = "key1",Value = 15.4 },new MyViewModel { Key = "key2",Value = 16.1 },new MyViewModel { Key = "key3",Value = 20 },};
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<MyViewModel> items)
    {
        return View(items);
    }
}

查看(?/ Views / Home / Index.aspx):

<% using (Html.BeginForm()) { %>
    <%: Html.EditorForModel() %>
    <input type="submit" value="OK" />
<% } %>

编辑模板(?/ Views / Home / EditorTemplates / MyViewModel.ascx):

<%@ Control 
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<Models.MyViewModel>" %>
<%: Html.HiddenFor(x => x.Key) %>
<%: Html.TextBoxFor(x => x.Value) %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读