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

2023-09-07 15:33:59 作者:基霸

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

I have created a special User Control which inherits KeyValuePair. Inside my ViewModel, there is a property called 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 字段的值.

The user Control has some Jquery statements which set the value of the TextBox and the Hidden field.

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

When I do a DEBUG to the POST method of the Controller, I see no value inside the Lookup property?!

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

But If I changed the type of the property to string instead of KeyValuePair and also change the type of the User Control, I see a value.

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

I think I'm very close but I can't figure it out.

推荐答案

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 )
{
     ...
}