MVC3 -发送字节数组到控制器-数据库RowVersion



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

我假设控制器序列化器(JsonValueProviderFactory)忽略了对象数组属性。

我看过这个博客,但是这并不适用,因为我发布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的回答更新:

我希望有一个更简洁的解决方案,但由于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 );
     }
  }

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

让它代替byte[],你的视图模型包含string属性,这是byte[]的base64表示。然后,您将不会有任何问题将其往返到客户端并返回到服务器,您将能够从Base64字符串中获得原始byte[]

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

最新更新