本文介绍了ModelBinder的前更改培养物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建不同语言的网站。我已经读过,我可以创造一个,但我有一个问题,豆蔻:结果
我曾为了与英语和德语数字格式( 123,456,789.1 123.456.789,1

I want to create a website in different languages. I already read that I could create an ActionFilter, but I have a litte problem:
I had to create a custom ModelBinder in order to work with english and german number formats (123,456,789.1 vs. 123.456.789,1)

public class DecimalModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        string key = bindingContext.ModelName;
        var v = ((string[])bindingContext.ValueProvider.GetValue(key).RawValue)[0];
        float outPut;
        if (float.TryParse(v, NumberStyles.Number, System.Globalization.CultureInfo.CurrentCulture, out outPut))
            return outPut;
        return base.BindModel(controllerContext, bindingContext);

    }
}

这ModelBinder的使用当前的文化来决定使用哪种格式。
但不幸的是,该模型绑定器使用前ActionFilter可以改变文化。

This ModelBinder uses the current culture to decide which format is used. But unfortunatly, the ModelBinder is used before the ActionFilter could change the culture.

如何修改的ModelBinder的变得活跃?

How can I change the culture before the ModelBinder becomes active?

推荐答案

您可以实现一个IHttpModule的,并设置文化在的BeginRequest,因为看到的。

You can implement an IHttpModule and set the culture in the BeginRequest, as seen here.

void context_BeginRequest(object sender, EventArgs e)
{
    // eat the cookie (if any) and set the culture
    if (HttpContext.Current.Request.Cookies["lang"] != null)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies["lang"];
        string lang = cookie.Value;
        var culture = new System.Globalization.CultureInfo(lang);
        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;
    }
}

这篇关于ModelBinder的前更改培养物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 17:46