MVC3(Razor)Json字符串化数据返回null(ArgumentNullException)

时间:2012-06-11 14:10:52

标签: asp.net-mvc json razor stringify

我有: 查看

<script type="text/javascript">
function postData() {
    var urlact = '@Url.Action("createDoc")';
    var model = '@Html.Raw(Json.Encode(Model))';

    alert(model);

    $.ajax({
        data: stringify(model),
        type: "POST",
        url: urlact,
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            window.location.href = '@Url.Action("CreateWordprocessingDocument","Movies")'
        }
    });
}
</script>

控制器

[HttpPost]
        public void createDoc(string mov)
        {
            var movies = new JavaScriptSerializer().Deserialize<IEnumerable<Movie>>(mov);
            //using movies...
        }

模型

//[Serializable]
public class Movie
{
    //Added Data Annotations for Title & Genre
    public int ID { get; set; }
    [Required(ErrorMessage = "Insert name")]
    public string Title { get; set; }
    [DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }
    [Required(ErrorMessage = "Inserist genre")]
    public string Genre { get; set; }
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }
}

为什么当我将View中的字符串化数据(通过Ajax post函数)发布到Controller(createDoc)时,它会停止抛出ArgumentNullException(似乎模型传递为空)? 任何变通方法/解决方案?

注意:如果没有对模型进行字符串化,那么它一切正常,但我正在尝试将其字符串化,导致另一种方式我遇到了DateTime格式的一些问题。

注意/ 2:我也尝试用 IEnumerable movies 替换Controller动作的输入参数中的 string mov ,但它也不起作用。

2 个答案:

答案 0 :(得分:0)

您的模型已经是JSON编码,因此您不需要对其进行字符串化。这可能导致无效的Json数据因此无法解码。

如果您的DateTime格式是问题,那么请解释该问题,以便我们帮助解决它。

答案 1 :(得分:0)

添加评论@Jaimal关于JSON.NET配置的回答。我使用以下内容:

public class JsonNetResult : JsonResult
    {
            public JsonNetResult()
            {
                Formatting = Formatting.None;
            }

            public Encoding ContentEncoding { get; set; }

            public string ContentType { get; set; }

            public object Data { get; set; }

            public JsonSerializerSettings SerializerSettings { get; set; }

            public Formatting Formatting { get; set; }

            public override void ExecuteResult(ControllerContext context)
            {
                if (context == null)
                    throw new ArgumentNullException("context");

                var response = context.HttpContext.Response;
                response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
                if (ContentEncoding != null)
                    response.ContentEncoding = ContentEncoding;

                if (Data == null)
                    return;
                // If you need special handling, you can call another form of SerializeObject below
                var serializedObject = JsonConvert.SerializeObject(Data, Formatting, new JavaScriptDateTimeConverter());

                response.Write(serializedObject);
            }
    }

public abstract class BaseController : Controller
{

            /// <summary>
            /// Use JSON.NET
            /// </summary>
            protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)
            {
                var result = new JsonNetResult
                                {
                                    Data = data,
                                    ContentType = contentType,
                                    ContentEncoding = contentEncoding,
                                                Formatting = Formatting.Indented
                                };

                return result;
            }

}

public JsonResult Get()
    {
            return Json(myModel, null, null);
    }

您可以使用不同的Converters