简体   繁体   English

将字典数据从视图传递到控制器

[英]pass dictionary data from view to controller

A while ago, I was trying to pass a dictionary data from my view to my controller. 前一段时间,我试图将字典数据从视图传递给控制器​​。 And I was able to do so after googling on the net(remember it was one of Scott Hanselman's posts). 在网路上搜寻之后,我得以做到(记住那是Scott Hanselman的帖子之一)。 The solution I had was something like 我的解决方案是这样的

<%for(int index=0; index<Model.Count(); index++){
     var property= Model.ElementAt(index);%>
     <input type="hidden" name="<%="properties["+index+"].Key"%>"/>
     <input type="hidden" name="<%="properties["+index+"].Value"%>"/>
<%}%>

public ActionResult Process(IDictionary<string,string> properties)
{
      doSomething();
      return View();
}

The code worked for awhile and then I did some refactoring and got rid of this chunk of code. 该代码工作了一段时间,然后我进行了一些重构,摆脱了这段代码。 Today, I ran into a situation in which I would like to pass a dictionary again. 今天,我遇到了想再次通过字典的情况。 But no matter how hard I try, the properties parameter received by the action was always null. 但是,无论我多么努力,该操作收到的properties参数始终为null。 I tried the above code and 我尝试了上面的代码,

<%for(int index=0; index<Model.Count(); index++){
     var property= Model.ElementAt(index);%>
     <input type="hidden" name="<%="properties.Keys["+index+"]"%>"/>
     <input type="hidden" name="<%="properties.Values["+index+"]"%>"/>
<%}%>

Neither code worked. 两种代码均无效。 I googled again but couldn't find the post that helped me before. 我再次谷歌搜索,但之前找不到帮助我的帖子。 Can someone point out what I did wrong? 有人可以指出我做错了什么吗? thanks a million. 太感谢了。

Update : It turned out that the problem is because the generated html code does not have continuous incrementing indexes. 更新 :事实证明,问题是因为生成的html代码没有连续的递增索引。 For instance, I was getting properties[0], properties[1], properties[3]...(properties[2] was missing). 例如,我正在获取属性[0],属性[1],属性[3] ...(缺少属性[2])。 So, firebug would be your best friend when encountering this kind of problems. 因此,当遇到此类问题时,firebug将是您最好的朋友。

You have your indexer in the wrong place, it has to be an index on the properties object. 您的索引器位置错误,它必须是Properties对象上的索引。

<%for(int index=0; index<Model.Count(); index++{
     var property= Model.ElementAt(index);%>
     <input type="hidden" name="<%="properties["+index+"].Key"%>"/>
     <input type="hidden" name="<%="properties["+index+"].Value"%>"/>
<%}%>

When i have this kind of problem i allways check the FormCollection Keys, to ensure that it contains the spectated keys, you can do this by putting a breakpoint at the ActionMethod. 当我遇到这种问题时,我总是检查FormCollection键,以确保它包含指定的键,您可以通过在ActionMethod上放置一个断点来做到这一点。

public ActionResult Process(IDictionary<string,string> properties, FormCollection f)

And check if "f" has the correct keys. 并检查“ f”是否具有正确的键。

You can also try 您也可以尝试

TryUpdateModel(properties, "properties");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM