1

I am learning about POST with Ajax and I've noticed a lot of examples using stringify on static arrays.

In my example I am building array via jQuery objects extracted from <input> values.

Jquery

    function PostEdit(vData){
        var content = JSON.stringify(vData); //content = "[{"Id":"1","Date":"7/12/2017 12:00:00 AM"}]"

            $.ajax({
                url: '@Url.Action("Index", "PostViewData")',
                type: "POST",
                data: JSON.stringify({ ViewData : vData }),
                contentType: "application/json",
                success: function (result) {
                    alert("success" + result);
                },
                error: function (result) {
                    alert("failure" + result);
                }
        });
        return;
    }

Controller

    [HttpPost]
    public ActionResult Index(List<DataViewModel> ViewData )
    {
        if(ViewData != null)
        {
            var json = new { success = true };
            return Json(json);
        }
        return Json(false);
    }

ViewModel

public class DataViewModel
{
    public DataViewModel(string id, string date)
    {
        Id = id;
        Date = date;
    }
    public string Id { get; set; }
    public string Date { get; set; }
}

Where DataViewModel is a class that consists of two values, Id, and Date which correspond to my JS object.

Since vData enters the function as value vData = [Object], When I call .stringify(vData) it returns content = "[{"Id":"1","Date":"7/12/2017 12:00:00 AM"}]"

The value of content above is how I see most examples structured before stringify such as the example here.

Once in this format, this is when most responses, examples call stringify anyway.

Now when I call .stringify(ViewData : vData) I dont even make it to the controller. Ajax fails to post. On the contrary when I call .stringify(ViewData : content), I make it to the controller, but with a null value. What am I missing / misunderstanding?

I'm looking for a better explanation of Ajax Post and Stringify, and how it interacts with the controller parameter.

lloyd
  • 1,089
  • 1
  • 17
  • 39

2 Answers2

1

Please try the solution below.
There's another way of doing this

    function PostEdit(vId, vDate){

        $.ajax({
            url: '/PostViewData/Index' // it should be '/controller/method'
            type: "POST",
            data: JSON.stringify({ Id: vId, Date: vDate}),  
            contentType: "application/json",
            success: function (result) {
                alert("success" + result);
            },
            error: function (result) {
                alert("failure" + result);
            }
    });
    return;
}


[HttpPost]
public ActionResult Index(string Id, string Date )
{
    if(Id != null)
    {
        var json = new { success = true };
        return Json(json);
    }
    return Json(false);
}

Update: In the controller method, it should be string id, string date
Update: The constructor should be parameterless. From the answer mentioned below

public DataViewModel()
{

}
Mohammed
  • 396
  • 4
  • 15
  • I had the stringify mostly as an example to show that data was actually there, I can stringify anywhere. I'd prefer to do inside of ajax generally. I just wanted to show the data was in `vData` to begin with. – lloyd Jul 12 '17 at 19:02
1

Just add parameterless constructor to your model. With that change, your code will work as it is. ASP is unable to parse your json as DataViewModel since it's trying to call default constructor that doesn't exists.

public class DataViewModel
{
    public DataViewModel()
    {

    }
    //...other methods and members here
}
derloopkat
  • 6,232
  • 16
  • 38
  • 45
  • This was the working solution. Is there any way I could have found this out through debugging? – lloyd Jul 12 '17 at 20:27
  • 1
    You won't see the exception thrown in VS as it happens before your code inside the action method runs. What I always do is checking Network tab in the browser inspector tool. Instead of a json response it returned default error page. Talking in general, I had came across this error message in a range of situations. Whenever you have a constructor that takes arguments, you are forced to create a parameterless constructor if it's going to be called. However if the class has no constructor whatsoever then you still can create instances without passing parameters. – derloopkat Jul 12 '17 at 20:58