0

I have: VIEW

<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>

Controller

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

Model

//[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; }
}

Why when I post the stringified data from View (through the Ajax post function) to Controller (createDoc) it stops throwing a ArgumentNullException (seems the Model passed is empty)? Any workaround/solution?

Note: without stringifying the model it all works, but I'm trying to stringify it cause the other way I've got some issues with the DateTime format.

Note/2: I've also tried replacing the string mov in the input parameters of the Controller action with IEnumerable movies, but it didn't work either.

Jesse
  • 8,223
  • 6
  • 49
  • 81
Jack88PD
  • 615
  • 2
  • 10
  • 24

2 Answers2

0

You'r model is already JSON encoded hence you do not need to Stringify it. This is probably causing Invalid Json data hence why it is not decoded.

if your DateTime format is the issue then explain that issue so we can help solve it.

Jaimal Chohan
  • 8,530
  • 6
  • 43
  • 64
  • The problem with the DateTime format is that when I print from the Controller the date passed to the Controller iteself, it prints *01/01/0001 00:00:00* for each Date. And I cannot do anything to modify/parse the passed Date cause I receive it directly in a IEnumerable variable in the controller action. – Jack88PD Jun 11 '12 at 14:22
  • If the problem is in JSON deserializer, may JSON.NET will be better. – napoleonss Jun 12 '12 at 08:32
  • Hi, @napoleonss thanks for your answer. I've tried to use JSON.NET with many samples founded on the web, but I cannot figured it out. Can you please post a sample code for the problem and its solution in json.net? Sorry for bothering you, thanks. – Jack88PD Jun 12 '12 at 13:54
0

Adding to the comment @Jaimal's answer about JSON.NET configuration. I use the following:

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

with

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

}

and

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

You may use different Converters.

Community
  • 1
  • 1
napoleonss
  • 1,139
  • 13
  • 19