结合非顺序列出了自定义模型粘合剂出了、粘合剂、自定义、顺序

2023-09-04 02:39:33 作者:为你绾发

我知道,如果我想非连续的元素绑定到一个列表中的MVC我可以使用所描述的首页语法的这里。

不过,我无法获得远程验证这一工作(使用的 远程 属性)。

例如,如果我有一个模型是这样的:

 公共类ADDUSERS {
    公开名单<使用者>用户{获得;组; }
    公共字符串评论{获得;组; }
}

公共类用户{
    [远程(UsernameAvailable,用户)]
    公共字符串名称{;组; }
}
 

然后,在我看来,假设我有以下的(我故意留出HTML辅助我使用的清晰度):

 <输入类型=隐藏名称=Users.Index值=富/>
<输入类型=文本名称=用户[富] .Name点/>

<输入类型=隐藏名称=Users.Index值=酒吧/>
<输入类型=文本名称=用户[巴] .Name点/>
 
空气化工 重点展示环氧胶黏剂 固化剂及促进剂

在一个表格后,在首页现场去凑凑热闹,这有助于模型绑定绑定一切很好,如:

Comment=bla&Users.Index=foo&Users[foo].Name=john&Users.Index=bar&Users[bar].Name=bob

但是,当远程验证触发器,仅这个被发送到我的动作(两个单独的请求,一个用于每个项目被验证):

 用户[FOO] .Name点=约翰
用户[巴] .Name点=鲍伯
 

如果没有一个首页,模型绑定不知道该怎么做与此有关。它既不能绑定到一个用户,一个列表<使用者> ,也不是 ADDUSER

这让我想起了我的问题。

会不会有一种方法来编写自定义模型绑定,可以处理非顺序列出,而无需使用首页符号?我必须承认,这是我很难明白为什么首页符号将是必要的(也许除了一些种类的优化)。

我用的MVC 4,和.NET 4.5。

注意:我从来没有搞砸周围的自定义模型粘合剂之前,所以我真的只是寻找一些关于它是否有可能(或只是一个死胡同)的一般指导,可能还有一些指针开始。

解决方案   

我能够从适应的解决方案,这个答案解决我的问题 - 埃里克·3月22日'13〜22: 28

I know that if I want to bind non-sequential elements to a list in MVC I can use the Index syntax described here.

However, I'm unable to get remote validation to work with this (using the Remote attribute).

For example, if I had a model like this:

public class AddUsers {
    public List<User> Users { get; set; }
    public string Comment { get; set; }
}

public class User {
    [Remote("UsernameAvailable", "User")]
    public string Name { get; set; }
}

Then suppose in my view I have the following (I'm deliberately leaving out Html helpers I'm using for clarity):

<input type="hidden" name="Users.Index" value="foo" />
<input type="text" name="Users[foo].Name" />

<input type="hidden" name="Users.Index" value="bar" />
<input type="text" name="Users[bar].Name" />

In a form post, the Index field goes along for the ride, which helps the model binder bind everything nicely, like:

Comment=bla&Users.Index=foo&Users[foo].Name=john&Users.Index=bar&Users[bar].Name=bob

But when remote validation triggers, only this is sent to my action (two separate requests, one for each item being validated):

Users[foo].Name=john
Users[bar].Name=bob

Without an Index, The model binder doesn't know what to do with this. It can neither bind to a User, a List<User>, nor an AddUser.

Which brings me to my question.

Would there be a way to write a custom model binder that can handle non-sequential lists without needing to use the Index notation? I must admit that it is difficult for me to see why the Index notation would be necessary (except perhaps as an optimization of some kind).

I'm using MVC 4, and .NET 4.5.

Note: I've never messed around with custom model binders before, so I'm really just looking for some general guidance about whether it would be possible (or just a dead end), and possibly some pointers for getting started.

解决方案

I was able to solve my problem by adapting the solution from this answer – Eric Mar 22 '13 at 22:28

 
精彩推荐
图片推荐