【问题标题】:ASP.NET MVC 3 binding user control of type KeyValuePair to ViewModelASP.NET MVC 3 将 KeyValuePair 类型的用户控件绑定到 ViewModel
【发布时间】:2011-12-16 18:57:42
【问题描述】:

我创建了一个继承 KeyValuePair 的特殊用户控件。 在我的 ViewModel 中,有一个名为 lookup 的属性

[UIHint("Lookup")]
public KeyValuePair<string, string> lookup { get; set; }

用户控制是

Html.TextBoxFor(m => m.Value, new { id = "Name", style = "width: 200px; background-color: #C0C0C0" })

Html.HiddenFor(m => m.Key, new { id="Guid"})

用户控件有一些 Jquery 语句来设置 TextBox 和 Hidden 字段的值。

当我对控制器的 POST 方法执行调试时,我在 Lookup 属性中看不到任何值?!

但是如果我将属性的类型更改为字符串而不是 KeyValuePair 并更改用户控件的类型,我看到了一个值。

我认为我很接近,但我无法弄清楚。

【问题讨论】:

    标签: asp.net asp.net-mvc-3 user-controls


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 非常感谢,这正是我想要的。
    • 如果使用实现了 > 的字典,为什么它不能正常工作?
    • @MarioLevrero 我假设(不检查)字典的模型绑定器使用 Add 方法来更新字典。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    相关资源
    最近更新 更多