Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC3 - posting byte array to a controller - Database RowVersion
    text
    copied!<p>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 side. When I attempt to post my view model to a controller, the RowVersion property is always null.</p> <p>I am assuming that the Controller serializer (JsonValueProviderFactory) is ignoring the Object array property.</p> <p>I have seen this blog, however this does not apply, as I am posting JSON and not the form markup: <a href="http://thedatafarm.com/blog/data-access/round-tripping-a-timestamp-field-with-ef4-1-code-first-and-mvc-3/">http://thedatafarm.com/blog/data-access/round-tripping-a-timestamp-field-with-ef4-1-code-first-and-mvc-3/</a></p> <p>My view renders my viewmodel like so:</p> <pre><code>&lt;script type="text/javascript"&gt; var viewModel = @Html.Raw( Json.Encode( this.Model ) ); &lt;/script&gt; </code></pre> <p>I then post the viewModel to the controller like so:</p> <pre><code> var data = { 'contact': viewModel }; $.ajax({ type: 'POST', url: '/Contact/Save', contentType: "application/json; charset=utf-8", data: JSON.stringify(data), dataType: 'json', success: function (data) { // Success }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.responseText); } }); </code></pre> <p>Here is my action in the controller:</p> <pre><code> [HttpPost] public JsonResult Save(Contact contact) { return this.Json( this._contactService.Save( contact ) ); } </code></pre> <p><strong>UPDATE:</strong> based on Darin's answer.</p> <p>I was hoping for a cleaner solution, but since Darin provided the only answer, I will have to add a custom property that will serialize my byte[] "row_version" property to a Base64 string. And when the Base64 string is set to the new custom property, it converts the string back to a byte[]. Below is the custom "RowVersion" property that I added to my model:</p> <pre><code> public byte[] row_version { get; set; } public string RowVersion { get { if( this.row_version != null ) return Convert.ToBase64String( this.row_version ); return string.Empty; } set { if( string.IsNullOrEmpty( value ) ) this.row_version = null; else this.row_version = Convert.FromBase64String( value ); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload