Razor and Dictionary
Razor and Dictionary

Feel like sharing?

I’m the first to admit I search Google / StackOverflow no less than 10 times a day for something. Oddly, the answer to this problem was a little hard to isolate. Most posts didn’t directly outline how to get two-way binding to work in a Razor page given a Dictionary as part of the view model.

So here it is, simple and sweet …

Razor Form Binding with a Dictionary

Given the sample view model:

public class MyViewModel
{
    public Dictionary<string, string> Books { get; set; }
}

The following Razor page will successfully iterate the dictionary and create input controls so that when the data is posted back, your view model dictionary will contain the new values:

@page
@model MyViewModel
@{
    Layout = "~/Pages/_Layout.cshtml";
}

@Html.AntiForgeryToken()

<form method="post">

<div class="row">
   <div class="col-12">
    @foreach(var item in Model)
    {                                    
       <div class="form-group row">
         <label class="col-lg-3 col-form-label">@item.Key</label>
         <div class="col-lg-9">
           <input asp-for="@Model[item.Key]" 
                    value="@item.Value" class="form-control">
        </div>
      </div>
    }
  </div>
</div>
<div class="row">
    <div class="col-sm-12 text-right">
        <button type="submit" class="btn btn-primary">Save</button>
     </div>
</div>

</form>

Feel like sharing?

Last modified: June 15, 2020

Author

Comments

Thanks, Feech!

Comments are closed.