ASP.NET MVC2 - 自定义模型绑定例子 [英] ASP.NET MVC2 - Custom Model Binder Examples

查看:92
本文介绍了ASP.NET MVC2 - 自定义模型绑定例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到建立一个自定义模型绑定为一个独特的结合情况,我需要处理的一些例子,但我发现的文章都是对旧版本的MVC这已不再MVC2相关。我一直在引用DefaultModelBinder源$ C ​​$ C,试图得到什么我需要做一般的感觉,但它完全不是我的情况比较复杂,我无法分离出特定的逻辑我需要实现。

I am trying to find some examples of building a custom model binder for a unique binding scenario I need to handle, but all of the articles I found were for older versions of MVC which are no longer relevant in MVC2. I've been referencing the DefaultModelBinder source code to try to get a general feel for what I need to do, but it's entirely more complicated than my scenario and I'm having trouble isolating the specific logic I need to implement.

我的目标是把复选框/文本框对的集合,并为所有经过对我想创建一个键/值对复选框的价值和相关的文本框的值。汇总这些数据后,我需要做的收集一些字符串序列化,所以我可以将其存储在所需的型号类型的字符串属性。我已经被在一个可管理的形式,这将让我给定的复选框涉及到一个特定的文本框的形式发送的数据,它只是一个搞清楚如何得到所有我需要他们的作品的问题。

My goal is to take a collection of Checkbox/Textbox pairs and for all of the Checked pairs I would like to create a key/value pair of the Checkbox's value and the associated Textbox's value. After aggregating this data I need to do some string serialization on the collection so I can store it in a string property of the desired Model type. I already the data being sent from the form in a manageable format which will allow me to relate a given Checkbox to a specific Textbox, it's just a matter of figuring out how to get all the pieces where I need them.

有谁知道能不能让我开始以建设一个自定义的模型绑定有的可达最新的教程?

Does anyone know of some up-to-date tutorials that can get me started with building a custom model binder?

推荐答案

我不知道为什么你觉得既然MVC 1发生了很多变化有关自定义模型粘合剂。但如果我明白你正在尝试做的,它应该是相当容易的。

I don't know why you think a lot has changed since MVC 1 regarding custom model binders. But If I understand what you are trying to do, it should be fairly easy.

public class CustomModelBinder : DefaultModelBinder {
    public override object BindModel(ControllerContext controllerContext, 
        ModelBindingContext bindingContext) {

        NameValueCollection form = controllerContext.HttpContext.Request.Form;
        //get what you need from the form collection

        //creata your model
        SomeModel myModel = new SomeMode();
        myModel.Property = "value";
        //or add some model errors if you need to
        ModelStateDictionary mState = bindingContext.ModelState;
        mState.Add("Property", new ModelState { });
        mState.AddModelError("Property", "There's an error.");

        return myModel; //return your model
    }
}

和你的行动:

public ActionResult Contact([ModelBinder(typeof(CustomModelBinder))]SomeModel m){
    //...
}

是那种你正在寻找的信息?

Was that the kind of information you are looking for?

这篇关于ASP.NET MVC2 - 自定义模型绑定例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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