使用form.serialize传递列表

时间:2017-11-06 07:34:02

标签: json ajax asp.net-mvc forms serialization

这是我的javascript函数,用于将数据从视图传递到控制器:

 function UpdateCourse() {
    debugger
    SelectedIncharge();
    SelectedAssistants();
    SelectedParticipants();
    var Course = $("form").serialize();
    var model = {
        courseData: Course,
        SelectedInchargeList: SelectedInchargeList,
        SelectedAssistantList: SelectedAssistantList,
        SelectedParticipantList: SelectedParticipantList           
    };
    debugger
    $.ajax({
        url: '@Url.Action("UpdateCourseDetails", "Course")',
        type: 'POST',
        dataType: 'JSON',
        data: model,
       // contentType: "application/json",
        success: function (data) {
            $('#CoursesSaveBtn').prop("disabled", false);
            ShowStatus(data.Response);
            hideWait();
            GetCourseGrid();
        },
        error: function (xhr) {
            $('#CoursesSaveBtn').prop("disabled", false);
            var response = { "ResponseCode": 99, "ResponseMessage": "Validation Failed" };
            var responseCode = JSON.parse(JSON.stringify(response));
            ShowStatus(responseCode);
            hideWait();
        }
    });
}

我在模型变量中获取值,但我只能正确列出courseData保持为null。这是我的视图模型代码。

public class CourseModel
{
    //public Guid Id { get; set; }
    //public string Name { get; set; }
    //public string Description { get; set; }
    //public string ClassRoom { get; set; }
    //public DatabaseOperationType Operation { get; set; }
    public CourseRequestDto courseData { get; set; }
    public List<Guid> SelectedInchargeList { get; set; }
    public List<Guid> SelectedAssistantList { get; set; }
    public List<Guid> SelectedParticipantList { get; set; }
}

我的控制器定义如下:

   [HttpPost]
    public ActionResult UpdateCourseDetails(CourseModel model)
    {
    }

1 个答案:

答案 0 :(得分:0)

$("form").serialize()返回带有序列化值的字符串,例如key1=value1&key2=value2。您的模型需要CourseRequestDto,因此在映射字符串而不是json时可能会出错。

我的猜测是你的courseData需要采用json格式。您可以参考此答案来获取表单数据:Convert form data to JavaScript object with jQuery