【问题标题】:MVC3 - posting byte array to a controller - Database RowVersionMVC3 - 将字节数组发布到控制器 - Database RowVersion
【发布时间】:2011-07-19 21:46:54
【问题描述】:

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

我假设控制器序列化程序 (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 提供了唯一的答案,我将不得不添加一个自定义属性,它将我的 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 );
     }
  }

【问题讨论】:

  • 嘿,你能发布你的控制器操作代码吗?
  • 嘿@Darin Dimitrov,你能添加serialization 标签吗?
  • See it。关于 SO 的类似问题
  • Tocco - 添加 jQuery.ajaxSettings.traditional 没有帮助

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


【解决方案1】:

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

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

【讨论】:

  • Convert.ToBase64String(byte[])
  • 非常好的解决方案(+1)!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多