MVC3 - posting byte array to a controller - Database RowVersion

前端 未结 2 1078
南笙
南笙 2020-12-30 22:00

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

相关标签:
2条回答
  • 2020-12-30 23:04

    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.

    0 讨论(0)
  • 2020-12-30 23:04

    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) };
    }
    
    0 讨论(0)
提交回复
热议问题