且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC 3 将 KeyValuePair 类型的用户控件绑定到 ViewModel

更新时间:2022-05-23 17:40:03

KeyValuePair 结构没有默认的无参数构造函数,不能被模型绑定器实例化.我为您的视图推荐一个只有这些属性的自定义模型类.

The KeyValuePair structure doesn't have a default parameterless constructor and can't be instantiated by the model binder. I recommend a custom model class for your view that has just those properties.

public class CustomControlViewModel
{
    public string Key { get; set; }
    public string Value { get; set; }
}

将您的 KVP 转换为该模型类以供您查看和/或将该类用作您的操作的参数.

Transform your KVP into this model class for your view and/or use this class as the parameter on your action.

[HttpGet]
public ActionResult Lookup()
{
    return View( new CustomControlViewModel { Value = kvp.Value, Key = kvp.Key } );
}

[HttpPost]
public ActionResult Lookup( CustomControlViewModel lookup )
{
     ...
}