1

In my .cshtml file I have the following

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

So in the above I have a Dictionary<string, string>. The key is already populated. I'd like the user to enter the value

The issue is when I click the save (submit) button, my controller's parameter Model.Range always shows null

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

And my viewmodel is simply

public class MyViewModel
{
    public Dictionary<string,string> Range{get;set;}
    //default constructor is here
}
MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120

2 Answers2

1

Add an parameter-less constructor to your ViewModel

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

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

Update

Also if you POST Data from the View (Client) to the Controller (Server) you have to capsuled it with 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>
    }
}
0

Need a parameter less constructor to initialize the Dictionary and add values

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

And in the view change it to so it is properly bound, see 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>
}
Community
  • 1
  • 1