Read request payload in c# asp.net ajax POST request

12,286

How do I access the data in my Home controller action ?

By writing a view model of course:

public class MyViewModel
{
    public DateTime Time { get; set; }
    public decimal OldValue { get; set; }
    public decimal? NewValue { get; set; }
    public string Action { get; set; }
}

and then having your controller action take a collection of this view model as a parameter:

[HttpPost]
public ActionResult TableEdit(IList<MyViewModel> data)
{
    ... do something with the view model here
}

By the way, beware of the format of DateTime fields. Make sure that your application's current culture settings format matches the one in your JSON. You also might need to adjust the data types used in your view model depending on your specific requirements.

Share:
12,286

Related videos on Youtube

lostpacket
Author by

lostpacket

Updated on August 03, 2022

Comments

  • lostpacket
    lostpacket almost 2 years

    I am sending a POST ajax request to Home controller in asp.net mvc project. Here is sample javascript. ( the convertUtcToLocal is basically a function that will return the time to local date ).

    var data = [{"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},
    {"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
    {"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
    {"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
    {"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
    {"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
    {"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
    {"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""},    
    {"Time":convertUtcToLocal(1377003600000),"OldValue":35.2,"NewValue":""}];
    
    $.ajax({url : 'http://localhost:64387/Home/TableEdit', 
            type : 'POST', 
            contentType:'application/json',
            dataType :'json', 
            data : JSON.stringify(data)});
    

    In Home controller I get ,

    [HttpPost]
            public object TableEdit(object data)
            {
                // object is shown in the Watch as object
    
            }
    

    In Google Chrome, I can see request payload enter image description here

    How do I access the data in my Home controller action ?

  • lostpacket
    lostpacket almost 11 years
    Is there any character limit on length of modelData string? I just want to make sure in case I am sending large data, I am not breaking the code.
  • 111
    111 almost 11 years
    There is no inherit size limit for JSON request itself. [For Asp.Net]If you return json from the server then, you can set MaxLength for it.