我需要在 Post 操作中获取模型属性,因此需要隐藏它们的元素,但我对 Dictionary <string, string>
类型有问题。这是我的模型:
public class ViewModel{
...
public ViewPart ViewPart { get; set; }
}
public class ViewPart {
...
public Dictionary<string, string> Flags { get; set; }
}
还有我的 Controller :
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);
查看中:
@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
}
但在后期操作中 Flags
总是为空,为什么?我的错在哪里?有没有更好的方法将变量从 View 传递到操作?
最佳答案
如果您想模型绑定(bind)到字典,则需要两个隐藏字段,一个用于Key
,另一个用于Value
:
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"/>
请注意,您还需要一个正在运行的索引以使模型绑定(bind)器满意。
或者,如果您不想运行,可以使用附加的隐藏 Index
字段来解决:
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"/>
}
您可以在这两篇文章中找到有关集合模型绑定(bind)的大量信息:
关于asp.net-mvc - ASP.NET MVC 3 中 Dictionary<string, string> 的隐藏输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11374097/