ASP.net MVC - 模型绑定不包括类字段? [英] ASP.net MVC - Model binding excludes class fields?

查看:26
本文介绍了ASP.net MVC - 模型绑定不包括类字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的一个项目中 - 我遇到了一个意想不到的障碍.
具有简单公共字段(注意不是属性)的类似乎不想与ASP.net MVC 3.0 模型绑定器.

In a recent project - i've hit an unexpected snag.
A class with simple public fields (note not properties) doesn't seem to want to play nice with the ASP.net MVC 3.0 model binder.

这是故意的吗?

除了将字段更改为属性 - 此处还有其他选项吗?

besides changing the fields to properties - any options here?

使用简单字段(而不是属性)的原因是因为我正在使用 MVC 和 Script Sharp 项目之间的共享库.脚本锐利支持属性 - 但它在视图中与 javascript 变得一团糟(使用knockout.js)

The reason for the simple fields (instead of properties) is because I'm working with a shared library between MVC and a Script Sharp project. Script sharp supports properties - but it becomes a mess with javascript in the view (using knockout.js)

因此,尽管我很喜欢(仅使用属性),但我还是在 dto 类中使用了公共字段.

So despite what i'd love (which is to just use properties) i'm using public fields in my dto classes.

我想避免对同一类有多个定义.叹气

I wanted to avoid having multiple definitions of the same classes. sigh

推荐答案

这是故意的吗?

是的,只有具有公共 getter/setter 的属性才能使用默认模型绑定器.

Yes, only properties with public getter/setters work with the default model binder.

除了将字段更改为属性 - 此处还有其他选项吗?

besides changing the fields to properties - any options here?

这就是你应该做的,因为无论如何你都应该使用视图模型.并且视图模型是专门为视图设计的.因此,将字段更改为属性是正确的做法.现在,如果您不遵循良好实践并尝试将域模型用作操作的输入/输出,那么您将不得不编写一个与字段一起使用的自定义模型绑定器.不过工作量会很大.

That's what you should do as you should be using view models anyway. And view models are specifically designed for the views. So changing the fields to properties is the correct way to do. Now if you don't follow good practices and try to use your domain models as input/output to actions then you will have to write a custom model binder that works with fields. It will be a lot of work though.

这篇关于ASP.net MVC - 模型绑定不包括类字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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