开发者

Dictionary<Enum, string>() won't bind to the Model in mvc

I'm trying to achieve something fairly simple but having some problem with the model binding.

public enum ColumnType
        {
            Column1 = 1,
            Column2 = 2,
            Column3 = 3,
            Column4 = 4,
            Column5 = 5,
            Column6 = 6,
            Column7 = 7,
            Column8 = 8,
            Column9 = 9
        }

Further in my viewModel I have a propery of type dictionary as follows :

public class PageViewModel {
        public IDict开发者_StackOverflow中文版ionary<ColumnType, string> Columns { get; set; }
}

Following is how my view looks like :

    <tr>
    <%  foreach (var value in Enum.GetValues(typeof(ColumnType)))
        {
            %>
                <%: Html.TextBox(String.Format("Columns[ColumnType.{0}]", value.ToString()))%>
            <%
        }
    %>
    </tr>

And I post above to the following POST method :

[POST]
public ActionResult Index(PageViewModel viewModel)
{
    var isNull = viewModel.Columns; //The model won't bind and 'isNull' is 'null' in here
    ...
    ...
}

As you can see, the 'viewModel.Columns' property is null on the POST action.

What am I missing here?

About result, it should look like following :

// pseudocode
Columns[0] = Key=Column1, Value="text1Value";
Columns[1] = Key=Column2, Value="text2Value";
...

I know there must be something like Columns[0].Key = Column1; Column[0].Value = "text1Value" inside the view, but I'm not sure.

Thanks a lot in advance you guys!


Try like this:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new PageViewModel
        {
            Columns = Enum.GetValues(typeof(ColumnType)).Cast<ColumnType>().ToDictionary(x => x, x => x.ToString())
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(PageViewModel model)
    {
        return View();
    }
}

and in the view:

<% using (Html.BeginForm()) { %>
    <% for (var i = 0; i < Model.Columns.Count; i++) { %>
        <%= Html.Hidden("Columns[" + i + "].Key", Model.Columns.ElementAt(i).Key) %>
        <%= Html.TextBox("Columns[" + i + "].Value", Model.Columns.ElementAt(i).Value) %>
    <% } %>
    <input type="submit" value="OK" />
<% } %>


Of course it will be null because you didn't initialize it.

You can write a constructor to the PageViewModel which instantiate (by new keyword) and fills the Columns with their corresponding values.

PageViewModel model = new PageViewModel();

Even though, I think you didn't explain your question enough, since the format you want to output to does not conform with what you described in the end of your question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜