如何通过按下提交按钮从jquery ajax调用将整个模型对象从视图传递到控制器操作?

时间:2016-01-18 07:18:54

标签: jquery ajax asp.net-mvc asp.net-mvc-4

我试过这样的话:

Ajax电话:

<script>

    $("#Create").click(function () {
        var project=@Model;
        $.ajax({
            url: "/Projects/TempCreateProject",
            datatype: "text",
            type: "POST",
            data: JSON.stringify(project),
            success: function (data) {
                alert(data.message);
            },
            error: function () {
                // $("#testarea").html("ERROR");
                alert("Error");
            }
        });
    });

</script>

操作方法

  [HttpPost]
         public ActionResult TempCreateProject(Project Project)
         {
             try
             {
                 var skill = _projectService.GetSkillSetById(Project.skillSetId);
                 Project.SkillSets.Add(skill);

                 var projectId = _projectService.AddProject(Project);
                 if (projectId >= 0)
                 {
                     var AlertMessage = Project.ProjectName + " Having ProjectId: " + projectId + " Created Successfully.";
                     return Json(new { success = true, message = "This is a message" });
                 }

                 return Json(new { success = false, message = "Project Creation Failed!!!" });
                 // return RedirectToAction("GetProjectList");
             }
             catch
             {
                 return View();
             }
         }

但这甚至没有调用行动方法..

1 个答案:

答案 0 :(得分:0)

您可以按照以下方式进行操作 -

// read values (example)
var data1 = $('#txt1').val();
var data2 = $('#txt2').val();

// Create your model
var modelData = { 'Name': data1, 'Code': data2 }; // Name and Code are the model properties

$("#Create").click(function () {
    $.ajax({
        url: "/Projects/TempCreateProject",
        datatype: "json",
        type: "POST",
        data: JSON.stringify({ Project: modelData }),
        contentType: "application/json; charset = utf-8"
        success: function (data) {
            alert(data.message);
        },
        error: function () {
            // $("#testarea").html("ERROR");
            alert("Error");
        }
    });
});