C#无法将我的模型绑定到剃刀TextBoxFor

时间:2017-02-21 13:38:54

标签: 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.Range.ElementAt(i).Key</p>
                </div>
                <div class="detail">
                    @Html.TextBoxFor(a => a.Range.ElementAt(i).Value)
                </div>
            </div>
        }

所以在上面我有一个Dictionary<string, string>。密钥已经填充。我希望用户输入值

问题是当我点击保存(提交)按钮时,我的控制器参数Model.Range始终显示为空

[HttpPost]
public ActionResult Edit(MyViewModel model)
{
//code. model.Range is always null
}

我的viewmodel就是

public class MyViewModel
{
    public Dictionary<string,string> Range{get;set;}
    //default constructor is here
}

2 个答案:

答案 0 :(得分:1)

向ViewModel添加无参数构造函数

public class MyViewModel
{
    public MyViewModel()
    {
        Range = new Dictionary<string, string>();
    }

    public Dictionary<string, string> Range { get; set; }
}

更新

此外,如果 POST数据从View(客户端)到Controller(服务器),您必须使用Html.BeginForm()

进行封装
@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>
    }
}

答案 1 :(得分:0)

需要一个参数less constructor来初始化Dictionary并添加值

public MyViewModel()
{
    Range = new Dictionary<string, string>();
    Range.Add("Item1", "value1");
}    

在视图中将其更改为已正确绑定,请参阅this answer

@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>
}