类型KeyValuePair到视图模型的ASP.NET MVC 3绑定的用户控件 [英] ASP.NET MVC 3 binding user control of type KeyValuePair to ViewModel

查看:129
本文介绍了类型KeyValuePair到视图模型的ASP.NET MVC 3绑定的用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个特殊的用户控制它继承KeyValuePair。
我的内部视图模型,有一个属性调用查找

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语句。

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

当我做了DEBUG到控制器的POST方法,我看到了查阅属性里面没有价值?

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 <​​/ code>结构不具有默认参数的构造函数,并且不能由模型实例化粘合剂。我推荐一个自定义的模型类为您的观点,即刚刚这些属性。

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

这篇关于类型KeyValuePair到视图模型的ASP.NET MVC 3绑定的用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆