2014-09-15 2 views
4

10 진수에 문제가 있습니다.ASP.NET MVC 5 응용 프로그램의 십진수

텍스트 상자에. (점) 대신. (쉼표)를 사용하면 컨트롤러에서 null이됩니다.

스페인어로는 십진수 대신 쉼표를 사용하지만 점을 사용해야하므로 언어 ​​문제가 있습니다.

변경할 수 있습니까? .

내가 float x = 3.14을 할 수 있지만, 나는 그렇게 내가 이것을 이해하지 못하는 float x = 3,14 할 수 없다 ... 어떤 경우에는 내가 가진 :

컨트롤러에서 내가 사용하기 때문에 그것은 이상하다 (점) 소수에 대한, 즉 모델에서

:

[Display(Name = "Total")] 
public double Total { get; set; } 
...

을 점 ... 내가 쉼표를 사용할 필요가 다른 사람을 사용하려면이 내 코드입니다 보기에서 6,

:

@Html.EditorFor(model => model.Total, new { id = "Total", htmlAttributes = new {@class = "form-control" } }) 

컨트롤러에서 :

public ActionResult Create([Bind(Include = "ID,Codigo,Fecha,Trabajo,Notas,BaseImponible,Iva,Total,Verificado,FormaDePagoID,ClienteID")] Presupuesto presupuesto) 
    { 
+1

만약 이것이 ASP.NET MVC라면 정확한 태그는 'asp.net-mvc'가 될 것입니다 (당신이 그것을 읽었을 때 설명이 명확해야합니다) – crashmstr

답변

0

컨트롤러는 C 번호를 사용합니다. 언어에 따라 .은 소수 구분 기호입니다. 기간. 언어별로 다르지 않습니다.

데이터베이스 또는 UI (서버의 언어 설정 사용)는 C#에서 사용하는 기본 (미국) 언어 설정 이외의 다른 소수 구분 기호를 사용할 수 있습니다. 그렇기 때문에 분리 자로 ,을 사용해야합니다.

0

을 게시 참조 (.) C#의 진수에 바인딩, 당신이 갈 수 있습니다 Asp.Net MVC의 사용자 정의 모델 바인더. 쉼표로 구분 된 10 진수 문자열을 사용하고 쉼표를 점으로 바꾸고 C# decimal 속성에 할당합니다.

이점은 응용 프로그램 전체에서 재사용이 가능하며 십진수 변환에 대한 반복적 인 시나리오가있는 것입니다. 다음 링크는 도움이

희망 :

ASP.Net MVC Custom Model Binding explanation http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx/

6

감사합니다 모두. 나는 꽤 잘 작동하는이 code from Phil Haack을 발견했다.

public class ModelBinder 
{ 
    public class DecimalModelBinder : DefaultModelBinder 
    { 
     public override object BindModel(ControllerContext controllerContext, 
             ModelBindingContext bindingContext) 
     { 
      object result = null; 

      // Don't do this here! 
      // It might do bindingContext.ModelState.AddModelError 
      // and there is no RemoveModelError! 
      // 
      // result = base.BindModel(controllerContext, bindingContext); 

      string modelName = bindingContext.ModelName; 
      string attemptedValue = 
       bindingContext.ValueProvider.GetValue(modelName).AttemptedValue; 

      // Depending on CultureInfo, the NumberDecimalSeparator can be "," or "." 
      // Both "." and "," should be accepted, but aren't. 
      string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator; 
      string alternateSeperator = (wantedSeperator == "," ? "." : ","); 

      if (attemptedValue.IndexOf(wantedSeperator) == -1 
       && attemptedValue.IndexOf(alternateSeperator) != -1) 
      { 
       attemptedValue = 
        attemptedValue.Replace(alternateSeperator, wantedSeperator); 
      } 

      try 
      { 
       if (bindingContext.ModelMetadata.IsNullableValueType 
        && string.IsNullOrWhiteSpace(attemptedValue)) 
       { 
        return null; 
       } 

       result = decimal.Parse(attemptedValue, NumberStyles.Any); 
      } 
      catch (FormatException e) 
      { 
       bindingContext.ModelState.AddModelError(modelName, e); 
      } 

      return result; 
     } 
    } 
} 

을 위해 Application_Start 글로벌() 메서드이 추가 프로젝트의 폴더에 클래스를 만듭니다.asax

ModelBinders.Binders.Add(typeof(decimal), new ModelBinder.DecimalModelBinder()); 
    ModelBinders.Binders.Add(typeof(decimal?), new ModelBinder.DecimalModelBinder()); 

이제 float 또는 double 대신 decimal type을 사용하면 모든 것이 잘됩니다 !! 친구가 주위를 둘러보십시오.

+0

똑같이 할 수 있고 여전히 두 번 사용할 수 있습니까? – Yoda

관련 문제