ASP.NET MVC Model Binder with Global Number Formats

前端 未结 2 1905
北荒
北荒 2020-12-10 15:30

The default model binder is returning errors for properties that are of type double when my application is being used in countries that use different number formatting for d

相关标签:
2条回答
  • 2020-12-10 15:46

    Take a look in this article but, for short, if you could try this:

    public ActionResult Create(FormCollection values)
    {
        Recipe recipe = new Recipe();
        recipe.Name = values["Name"];      
    
        // ...
    
        return View();
    }
    

    ...or this, in case you have a Model:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Recipe newRecipe)
    {            
        // ...
    
        return View();
    }
    

    The article has complete references and other ways of doing this. I use these 2 and they were enough for me up to now.

    0 讨论(0)
  • 2020-12-10 15:57

    You want your application to use a single culture, right? If so, you can do this with the globalization tag of your web.config.

    <configuration>
        <system.web>
            <globalization
               enableClientBasedCulture="true"        
               culture="en-GB"
               uiCulture="en-GB"/>
        </system.web>
    </configuration>
    

    And then you can forget those custom model binder and use the default.

    UPDATE: Ok, it's a multi-language application. How do you get the culture you want? Can you call createCulture on the MvcApplication class? You could do this:

    public class MvcApplication : HttpApplication
    {
        //...
        public void Application_OnBeginRequest(object sender, EventArgs e)
        {
            CultureInfo culture = GetCulture();
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }
        //...
    }
    

    This method is called before the model bind, so, again, you won't need the custom model binder. I hope it works for you :)

    0 讨论(0)
提交回复
热议问题