- MVC3 model DisplayFormat and JSON
- [DisplayFormat(DataFormatString = "{0:P2}")]
- public Nullable<double> Yearly_act_pct { get; set; }
- @Html.DisplayFor(modelItem => item.Yearly_act_pct)
- return Json(myObjects, JsonRequestBehavior.AllowGet);
- JavaScriptSerializer serializer = new JavaScriptSerializer();
- response.Write(serializer.Serialize(Data));
- 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);
- [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; }
- 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;
- }
- 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);
- }