C#can';t将我的模型绑定到razor TextBoxFor
在我的.cshtml文件中,我有以下内容C#can';t将我的模型绑定到razor TextBoxFor,c#,dictionary,razor,C#,Dictionary,Razor,在我的.cshtml文件中,我有以下内容 @model MyProject.MyViewModel.Range @for (int i = 0; i < Model.Range.Count; i++) { <div class="wrapper"> <div class="detail"> <p class="bold">@Model.Ra
@model MyProject.MyViewModel.Range
@for (int i = 0; i < Model.Range.Count; i++)
{
<div class="wrapper">
<div class="detail">
<p class="bold">@Model.Range.ElementAt(i).Key</p>
</div>
<div class="detail">
@Html.TextBoxFor(a => a.Range.ElementAt(i).Value)
</div>
</div>
}
我的viewmodel很简单
public class MyViewModel
{
public Dictionary<string,string> Range{get;set;}
//default constructor is here
}
公共类MyViewModel
{
公共字典范围{get;set;}
//默认构造函数在这里
}
将无参数构造函数添加到ViewModel中
public class MyViewModel
{
public MyViewModel()
{
Range = new Dictionary<string, string>();
}
public Dictionary<string, string> Range { get; set; }
}
需要一个无参数构造函数来初始化字典和添加值
public MyViewModel()
{
Range = new Dictionary<string, string>();
Range.Add("Item1", "value1");
}
publicMyViewModel()
{
范围=新字典();
范围。添加(“项目1”、“价值1”);
}
在视图中,将其更改为,以使其正确绑定,请参见
@foreach(Model.Range中的var kvp)
{
@kvp.Key
@Html.TextBoxFor(a=>a.Range[kvp.Key])
}
如果是这样的话,我想编译器@Smartis会责备我,但是,我有默认的构造函数。谢谢我不是在字典上签首字母我是。。。。好的,这将停止它为null
,但我仍然没有看到任何值。这是一个空房间Dictionary@MyDaftQuestions使用调试器检查控制器是否提供了正确的ViewModel。断点应该可以正常工作。
@model MyProject.MyViewModel.Range
@using(Html.BeginForm())
{
@for (int i = 0; i < Model.Range.Count; i++)
{
<div class="wrapper">
<div class="detail">
<p class="bold">@Model.Range.ElementAt(i).Key</p>
</div>
<div class="detail">
@Html.TextBoxFor(a => a.Range.ElementAt(i).Value)
</div>
</div>
}
}
public MyViewModel()
{
Range = new Dictionary<string, string>();
Range.Add("Item1", "value1");
}
@foreach (var kvp in Model.Range)
{
<div class="wrapper">
<div class="detail">
<p class="bold">@kvp.Key</p>
</div>
<div class="detail">
@Html.TextBoxFor(a => a.Range[kvp.Key])
</div>
</div>
}