mvc6自定义模型活页夹不触发 [英] mvc6 custom model binder not firing

查看:97
本文介绍了mvc6自定义模型活页夹不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出当前mvc6(Visual Studio 2015发行候选版本)中的模型绑定. 到目前为止,这是我的代码:

I'm trying to figure out model binding in current mvc6 (visual studio 2015 release candidate). This is what my code looks like so far:

public class MyObjectModelBinder : IModelBinder
{
    public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
    {

        if (bindingContext.ModelType == typeof(MyObject))
        {
            var model = new MyObject();
            return Task.FromResult(new ModelBindingResult(model, bindingContext.ModelName, true));
        }
        return Task.FromResult<ModelBindingResult>(null);

    }
}

startup.cs中的注册

The registration in startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().Configure<MvcOptions>(options =>
    {
        options.ModelBinders.Add(typeof( MyObjectModelBinder));
    });
}

我的控制器:

[HttpPost]
public void ReceiveMyObject([FromBody] MyObject x)
{

}

我还不关心从输入中实际创建对象,麻烦的是,当我调试时,我看到控制器触发(x为空),但是没有调用绑定函数. 对这里出什么问题有任何想法吗?

I don't care yet about actually creating the object from the input, what troubles me is that when I debug, I see the controller firing (with x being null), but the binder function is not being called. Any ideas of what's wrong here?

另外请注意,我已经看过

Also note, I have already seen What is the correct way to create custom model binders in MVC6? but the answer in that post is either wrong or outdated, since the example provided doesn't implement the current IModelBinder.

谢谢

这是用于触发控制器的javascript代码:

This is the javascript code used to fire the controller:

function sendMessage(i) {
    $.ajax({
        type: 'POST',
        url: 'myurl',
        data: data,
        contentType: 'application/x-www-form-urlencoded',
        dataType: 'json',
        success: function (data) { console.log(data) }
    });
}

推荐答案

添加

public void ReceiveMyObject([ModelBinder(BinderType = typeof(MyObjectModelBinder))] MyObject x)

方法或u可以为类型设置默认的资料夹

to method or u can set default binder for type

这篇关于mvc6自定义模型活页夹不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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