控制器没有获得发布数据

时间:2011-11-23 01:30:59

标签: c# json asp.net-mvc-3

我正在使用jquery UI datepicker将fromto日期发送到控制器。我的问题是控制器没有获得发布数据。

在我的观点中:

to_date.datepicker({
    dateFormat: 'yy-mm-dd',
    onSelect: function (selectedDate, inst) {
        if (from_date.datepicker("getDate") > to_date.datepicker("getDate")) {
        // error check
        } else {
            var from = from_date.val();
            var to = selectedDate;

            var data = {
                FromDate: from,
                ToDate: to
            };

            var jsonData = JSON.stringify(data);

            $.ajax({
                type: 'POST',
                url: 'View',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                cache: false,
                data: jsonData
            });
        }
    }
});

在我的控制器中:

[HttpPost]
public JsonResult DorView(string dates)
{
    if (ModelState.IsValid)
    {

        JavaScriptSerializer js = new JavaScriptSerializer();

        // Will die on this line because dates is empty
        DatePicker JsonDate = js.Deserialize<DatePicker>(dates);

        return Json(dates);
    }

    return Json(dates);
}

2 个答案:

答案 0 :(得分:2)

您无需在控制器中手动执行JSON反序列化。只需使用视图模型并让默认模型绑定器完成工作。

所以定义一个视图模型

public class Dates
{
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }
}

并让您的控制器操作将此视图模型作为参数:

[HttpPost]
public ActionResult DorView(Dates dates)
{
    if (ModelState.IsValid)
    {
        // do something with dates.FromDate and dates.ToDate

        return Json(dates);
    }

    return Json(dates);
}

答案 1 :(得分:0)

您需要使用名为dates的密钥发送密钥值对。

        $.ajax({
            type: 'POST',
            url: 'View',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            data: "dates=" + jsonData
        });
相关问题