MVC3 - 将字节数组发布到控制器 - Database RowVersion

时间:2011-07-19 21:46:55

标签: asp.net-mvc serialization razor byte rowversion

我正在研究MVC3应用程序。我的客户端ViewModel包含一个SQL Server RowVersion属性,它是一个byte []。它在客户端呈现为Object数组。当我尝试将我的视图模型发布到控制器时,RowVersion属性始终为null。

我假设Controller序列化程序(JsonValueProviderFactory)忽略了Object数组属性。

我见过这个博客,但是这不适用,因为我发布的是JSON而不是表单标记: http://thedatafarm.com/blog/data-access/round-tripping-a-timestamp-field-with-ef4-1-code-first-and-mvc-3/

我的视图呈现我的视图模型:

<script type="text/javascript">
  var viewModel = @Html.Raw( Json.Encode( this.Model ) );
</script>

然后我将viewModel发布到控制器,如下所示:

    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);
        }
    });

以下是我在控制器中的操作:

  [HttpPost]
  public JsonResult Save(Contact contact) {
     return this.Json( this._contactService.Save( contact ) );
  }

更新:基于达林的答案。

我希望有一个更清晰的解决方案,但由于Darin提供了唯一的答案,我将不得不添加一个自定义属性,将我的byte []“row_version”属性序列化为Base64字符串。当Base64字符串设置为新的自定义属性时,它会将字符串转换回byte []。下面是我添加到我的模型中的自定义“RowVersion”属性:

  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 );
     }
  }

2 个答案:

答案 0 :(得分:36)

  

我的客户端ViewModel包含一个SQL Server RowVersion属性,它是一个byte []

使其成为byte[],而不是string您的视图模型包含byte[]属性,该属性是此byte[]的{​​{3}}表示形式。然后,您将没有任何问题将其转发到客户端并返回到服务器,在那里您将能够从Base64字符串中获取原始{{1}}。

答案 1 :(得分:1)

Json.NET自动将字节数组编码为Base64。

您可以使用JsonNetResult代替JsonResult

来自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);
    }
}

用法:

[HttpPost]
public JsonResult Save(Contact contact) {
    return new JsonNetResult { Data = _contactService.Save(contact) };
}