locked
adding date range parameter $.getJSON to integrate with controller json asp mvc RRS feed

  • Question

  • User2131089582 posted

    I want to parameters range date in getjson jquery here is my code

         var params = { from: "28-11-2019", to: "01-12-2019" };
                    $.getJSON('/searchstatistics/GetData', params, function (data) {
            //another code goues here
    });

    Here is my controller

    public JsonResult GetData(DateTime from, DateTime to)
    {
      //another code goes here
    }

    here is the generated request url on network http://localhost:35039/searchstatistics/GetData?from=28-11-2019&to=01-12-2019 I got error below

    The parameters dictionary contains a null entry for parameter 'from' of non-nullable type 'System.DateTime' for method 'System.Web.Mvc.JsonResult GetData(System.DateTime, System.DateTime)'

    I'm sure the problem is from params of date, i don't know why, Can you help me to figure out

    Sunday, December 1, 2019 5:23 AM

Answers

  • User-719153870 posted

    Hi hocamahdi99,

    The parameters dictionary contains a null entry for parameter 'from' of non-nullable type 'System.DateTime' for method 'System.Web.Mvc.JsonResult GetData(System.DateTime, System.DateTime)'

    The reason for this problem is that you were trying to pass a from value with incorrect format to your GetData method.

    The correct method for a datetime type value in c# should be like MM-DD-YYYY, YYYY-MM-DD, YYYY/MM/DD or MM/DD/YYYY etc but not DD-MM-YYYY.

    Please modify your code like below demo:

    cshtml:

    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>FromToDemo</title>
        <script src="~/Scripts/jquery-3.3.1.min.js"></script>
        <script>
            function get() {
                var params = { from: "11-28-2019", to: "12-01-2019" };
                $.getJSON('/Demo/GetData', params, function (result) {
                    alert(result);
                });
            }
        </script>
    </head>
    <body>
        <div> 
            <input type="button" value="Get" onclick="get()" />
        </div>
        <p></p>
    </body>
    </html>

    cs:

    public ActionResult FromToDemo()
            {
                return View();
            }
            
            public JsonResult GetData(DateTime from, DateTime to)
            {
                string a = from.ToString()+"abc"+to.ToString();
                return Json(a, JsonRequestBehavior.AllowGet);
                //another code goes here
            }

    Below is the result of above demo:

    Best Regard,

    Yang Shen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 2, 2019 2:32 AM