C#将Json字符串发布到实体模型

时间:2015-06-16 14:46:59

标签: c# jquery json asp.net-mvc entity-framework

我正在尝试发布一个Json字符串,对其进行反序列化,然后使用MVC实体框架将其保存到SQL数据库中。这是我的模特:

[Serializable]
public partial class employee
{
    public int id { get; set; }
    public string netid { get; set; }
    public string enumber { get; set; }
    public string peoplesoft { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string mi { get; set; }
    public string prefix { get; set; }
    public string suffix { get; set; }
    public string email { get; set; }
    public string tenure_year { get; set; }
    public byte tenure_indicator { get; set; }
    public Nullable<System.DateTime> hire_date { get; set; }
    public string updated_by { get; set; }
    public System.DateTime created_at { get; set; }
    public System.DateTime updated_at { get; set; }
    public string gender { get; set; }
    public Nullable<System.DateTime> birth_date { get; set; }
}

我的控制器:

[HttpPost]
    public ActionResult Create(ChadAPI.Models.Lookup.employee employee)
    {
        if (ModelState.IsValid)
        {

            db.employees.Add(employee);
            db.SaveChanges();
            return new JsonResult() { Data = employee, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

        }

        return Content("Model State Invalid");
    }

和我的观点:

@model ChadAPI.Models.Lookup.employee

@{
ViewBag.Title = "Create";
}
<script src="~/Scripts/jquery-1.10.2.intellisense.js"></script>

<h2>Create</h2>


<input type="submit" id="Save" value="Save" />

<script>
$(function () {
    $("#Save").click(function () {
        alert("clicked!");
        var employee = {
            id: 77,
            netid: 'caw63231',
            enumber: '00000',
            peoplesoft: '1012481',
            firstname: 'Christian',
            updatedby: 'caw63231',
            createdat: '10/14/2013 3:02:46 PM',
            updatedat: '10/14/2013 3:02:46 PM'
        }
        $.ajax({
            type: "POST",
            url: "Employees/Create",
            data: employee,
            success: function (data) {
                console.log("success!")
            },
            dataType: "json",
            traditional: true
        });
    });
});
</script>

当我在视图中按下按钮时没有任何反应,并且使用Fiddler我可以看到没有任何JSON被传递。我做错了什么?

2 个答案:

答案 0 :(得分:3)

MVC会自动将JSON请求映射到您的Actions参数。您编写的操作将期待一个字符串对象,并且您尝试将其发布为包含数组的JSON对象。

您应该更新您的操作以接收Employee对象,并将该JSON表示形式发布到该操作。像这样:

$(function () {
$("#Save").click(function () {
    var employee = {
            id: 77,
            netid : 'cfw22511',
            enumber : '000000',
            peoplesoft : '2322381'
             //..... Add the rest of your data to the JSON object
        };
    $.ajax({
        type: "POST",
        url: "/Employees/Create",
        data: employee,
        success: function(data){
            alert(data.Result)
        },
        dataType: "json",
        traditional: true
    });
});

});

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(CreateChadAPI.Models.Lookup.employee employee)
    {
        if (ModelState.IsValid)
        {
            db.employees.Add(employee);
            db.SaveChanges();
            db.SaveChanges();
            return new JsonResult() {Data = employee, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
        }
        return Content("Model State Invalid");
    }

答案 1 :(得分:0)

Json是一个解析为字符串的对象,当将此对象发送到服务器时,MVC会自动将其转换为对象,您不必自己执行此操作,因此:

public ActionResult Create(ChadAPI.Models.Lookup.employee jsonemployee)

另一方面,创建相同的对象&#39;在Js:

var emp = new Object() { ID:777, }

另外,请检查您的javascript代码是否正在运行