I am working on an MVC3 application. My client side ViewModel contains a SQL Server RowVersion property, which is a byte[]. It is rendered as an Object array on the client
My client side ViewModel contains a SQL Server RowVersion property, which is a byte[]
Make it so that instead of a byte[]
your view model contains a string
property which is the base64 representation of this byte[]
. Then you won't have any problems roundtripping it to the client and back to the server where you will be able to get the original byte[]
from the Base64 string.
Json.NET automatically encodes byte arrays as Base64.
You can use JsonNetResult
instead of JsonResult
:
from https://gist.github.com/DavidDeSloovere/5689824:
using System;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class JsonNetResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/json";
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data == null)
{
return;
}
var jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var formatting = HttpContext.Current != null && HttpContext.Current.IsDebuggingEnabled ? Formatting.Indented : Formatting.None;
var serializedObject = JsonConvert.SerializeObject(Data, formatting, jsonSerializerSettings);
response.Write(serializedObject);
}
}
Usage:
[HttpPost]
public JsonResult Save(Contact contact) {
return new JsonNetResult { Data = _contactService.Save(contact) };
}