对于字典和LT隐藏的输入,串,串>在ASP.NET MVC 3 [英] Hidden input for Dictionary<string, string> in ASP.NET MVC 3

查看:121
本文介绍了对于字典和LT隐藏的输入,串,串>在ASP.NET MVC 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在后的行动我的模型属性,因此需要为他们隐藏的元素,但我有键入的问题词典<字符串,字符串> 。这是我的模型:

I need to get my model properties in Post action, so need to hidden element for them, but I have a problem with type of Dictionary <string, string>. this is My model:

public class ViewModel{
 ...
 public ViewPart ViewPart { get; set; }
}

public class ViewPart {
 ...
 public Dictionary<string, string> Flags { get; set; }
}

和我的控制器:

Dictionary<string, string> flags = new Dictionary<string, string>();
flags.Add("kind", "Edit");
flags.Add("Command", "Save");
ViewModel model = new ViewModel(){ Flags  = flags };
return View(model);

在View:

@foreach(var item in Model.ViewPart.Flags) { 
 <input type="hidden" id="ViewPart_Flags_@(item.Key)" value="@item.Value" name="ViewPart.Flags[@(item.Key)]" />
}

我也试试这个:

@foreach(var item in Model.ViewPart.Flags) { 
  @Html.HiddenFor(modelItem => item)
}

更新
帖子动作:

[HttpPost]
public ActionResult MyPostAction(ViewModel model){
  //model.ViewPart.Flags is null
}

但在行动后的标记总是空的,为什么?哪里是我的错吗?有没有更好的方式来传递从视图变量给动作?

But in Post action the Flags is Always null, why? where is my fault? Is there any better way to pass variables from View To Action?

推荐答案

您需要两个隐藏字段一个是,一个用于如果你想modelbind字典:

You need two hidden fields one for the Key and one for the Value if you want to modelbind to a dictionary:

var index = 0;
foreach (var item in Model.ViewPart.Flags)
{

    <input type="hidden" value="@item.Key" 
                         name="ViewPart.Flags[@(index)].Key"/>
    <input type="hidden" value="@item.Value" 
                         name="ViewPart.Flags[@(index)].Value"/>

    index++;
}
    <input type="submit" value="Save"/>

请注意,您将还需要一个正在运行的指标,使模型绑定开心。

Note, you will be also need a running index to make the model binder happy.

或者,如果你不希望有一个正在运行的,你可以用一个addtional隐藏首页字段解决:

Or if you don't want to have a running you can solve with an addtional hidden Index field:

foreach (var item in Model.ViewPart.Flags)
{

    <input type="hidden" value="@item.Key" 
                         name="ViewPart.Flags.Index"/>
    <input type="hidden" value="@item.Key" 
                         name="ViewPart.Flags[@(item.Key)].Key" />
    <input type="hidden" value="@item.Value" 
                         name="ViewPart.Flags[@(item.Key)].Value" />
}
    <input type="submit" value="Save"/>
}

您可以找到大量的信息关于这个两篇文章与收藏modelbinding:

You can find a lots of info about modelbinding with collections in this two article:

  • ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries
  • Model Binding To A List

这篇关于对于字典和LT隐藏的输入,串,串&GT;在ASP.NET MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆