MVC。绑定到TextBoxFor类型对象的字段 [英] MVC. Bind TextBoxFor to a Field of type object

查看:336
本文介绍了MVC。绑定到TextBoxFor类型对象的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下code:

public class Person 
{
    public object Age { get; set;}
}

内部视图:

@Html.TextBoxFor(x => x.Age, new { @type = "number" })

现在发布表单时,将typeof person.Age 属性是字符串[1] 。为什么呢?

Now when posting the Form, the typeOf person.Age property is string[1]. Why?

不应该有一些输入型为主,键入回升的逻辑,结合东西的时候?

Shouldn't there be some input type based, Type pick-up logic, when binding things?

推荐答案

您无法使用 *对于与类型的属性助手对象。这些助手需要做类型推断,以创建具有正确的名称和属性正确类型的输入。一个对象可以从字面上的任何

You can't use the *For helpers with a property of type object. These helpers need to do type inference in order to create the right type of input with the right name and attributes. An object could literally be anything.

我不知道为什么你使用对象年龄属性(不说相当明显的一个 INT ?)。但是,如果你真正需要做的,我会建议使用视图模型,你可以定义一个更具体的类型视图的目的。然后,您可以张贴的价值只是映射回到你的对象属性。

I'm not sure why you're using object for a property like Age (isn't that fairly obviously a int?). However, if you truly need to do that, I would recommend using a view model where you can define a more concrete type for the purposes of your view. Then, you can simply map the posted value back onto your object property.

这篇关于MVC。绑定到TextBoxFor类型对象的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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