ASP.NET MVC 3 binding user control of type KeyValuePair to ViewModel(ASP.NET MVC 3 将 KeyValuePair 类型的用户控件绑定到 ViewModel)
问题描述
我创建了一个继承 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 )
{
...
}
这篇关于ASP.NET MVC 3 将 KeyValuePair 类型的用户控件绑定到 ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ASP.NET MVC 3 将 KeyValuePair 类型的用户控件绑定到 ViewModel
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01