.net MVC3模型DisplayFormat和JSON
我有一个模型,上面有一些double属性,它附带了一个DisplayFormat,可以将double转换成一个可读的百分比。。范例.net MVC3模型DisplayFormat和JSON,.net,asp.net-mvc,asp.net-mvc-3,.net,Asp.net Mvc,Asp.net Mvc 3,我有一个模型,上面有一些double属性,它附带了一个DisplayFormat,可以将double转换成一个可读的百分比。。范例 [DisplayFormat(DataFormatString = "{0:P2}")] public Nullable<double> Yearly_act_pct { get; set; } 然而,当我将其中一些对象转储到JSON提要中时,DisplayFormats似乎被忽略了,因此我最终得到了原始小数,通常是大小数 我怎么做这个 return
[DisplayFormat(DataFormatString = "{0:P2}")]
public Nullable<double> Yearly_act_pct { get; set; }
然而,当我将其中一些对象转储到JSON提要中时,DisplayFormats似乎被忽略了,因此我最终得到了原始小数,通常是大小数
我怎么做这个
return Json(myObjects, JsonRequestBehavior.AllowGet);
是否尊重DisplayFormats?命名空间属性将仅处理动态数据控件和显示格式的
数据注释。在将对象传递给Json()
方法之前,您需要做的只是一些基本的舍入。这样就足够了:
myObjects.Yearly_act_pct = Math.Round(myObjects.Yearly_act_pct, 2); // provided you wanted to round to nearest two fractional digits
return Json(myObjects, JsonRequestBehavior.AllowGet);
这将为您提供“小双精度”值,但您仍在传递一个double
,而不是可以格式化为double
的字符串。不确定这是否有意义,但是double
是double
,您所能做的最好的事情就是将它四舍五入,这样它就不会有多余的小数位数。调用返回Json(myObjects,JsonRequestBehavior.AllowGet)
实际上返回一个JsonResult
。JsonResult
的内部执行调用:
JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(serializer.Serialize(Data));
如果你看MSDN,你会发现有一个简单的转换。此实现似乎不支持DisplayFormat
您可以编写一个派生自JsonResult
的类,该类接受DisplayFormat属性。在处理序列化时,当需要自定义输出格式时,人们一直使用的解决方法之一是创建字符串属性:
[DataMember(Name = "price", Order = 23)]
[XmlElement("price", Order = 23)]
public string Price_String
{
get
{
return Formatter.FormatAsCurrency(this.Price);
}
set
{
this.Price = Formatter.ParseCurrency(value);
}
}
[XmlIgnore]
public decimal Price { get; set; }
Formatter是我拥有的一个自定义类,它处理特定类型的解析/格式化。这些不相关,但我将包括:
public static string FormatAsCurrency(decimal? amount)
{
return amount.HasValue ? String.Format("{0:C}USD", amount).Replace("$","") : null;
}
public static decimal ParseCurrency(string value)
{
return !String.IsNullOrEmpty(value) ? decimal.Parse(value.Replace("USD", "")) : 0;
}
public static decimal? ParseNullableCurrency(string value)
{
return !String.IsNullOrEmpty(value) ? decimal.Parse(value.Replace("USD", "")) as decimal? : null;
}
在我的示例中,我标记了DataContract和Xml序列化的属性。这并不理想,但当时是唯一的解决办法
我还在控制器中创建了一个方法来返回响应“
使用它:
public ActionResult Feed()
{
ViewModels.API.Deals.Response response = new ViewModels.API.Deals.Get();
return GetContentResult(response);
}
我的示例比您正在使用的要复杂一点,但它可以工作(对于XML和JSON)以编程方式,如何读取对象的属性DisplayFormat设置?
public ContentResult GetContentResult(object responseObject)
{
#region Output Format
if (this.ResponseFormat == ResponseFormatEnum.JSON)
{
string json = "";
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer jsonserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(responseObject.GetType());
MemoryStream ms = new MemoryStream();
jsonserializer.WriteObject(ms, responseObject);
json = Encoding.Default.GetString(ms.ToArray());
ms.Close();
ms.Dispose();
jsonserializer = null;
}
catch(System.Exception ex)
{
string err = ex.Message;
}
return new ContentResult() { Content = json, ContentType = "application/json" };
}
else
{
string xml = "";
try
{
MemoryStream ms = new MemoryStream();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(responseObject.GetType());
System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
ns.Add("", "");
ms = new MemoryStream();
serializer.Serialize(ms, responseObject, ns);
xml = Encoding.Default.GetString(ms.ToArray()); ms.Close();
ms.Dispose();
serializer = null;
}
catch (System.Exception ex)
{
throw ex;
}
return new ContentResult() { Content = xml, ContentType = "text/xml" };
}
#endregion
}
public ActionResult Feed()
{
ViewModels.API.Deals.Response response = new ViewModels.API.Deals.Get();
return GetContentResult(response);
}