使用自定义类中的json保存数据

时间:2016-02-12 09:42:49

标签: c# json asp.net-mvc-4 model-view-controller json.net

我仍在尝试理解这个ajax。

我正在尝试将患者从js保存到服务器端的数据库,但下面的代码总是导致[alert(“error”)]

有人能看到错误吗?

MVC行动:

public JsonResult CreatePatient(string patient)
{
    var jsonPatient = JsonConvert.DeserializeObject<Patient>(patient);

    if (db.Patients.Contains(jsonPatient))
    {
        db.Patients.Remove(jsonPatient);
    }
    db.Patients.Add(jsonPatient);

    return new JsonResult();
}

自定义类:

public class Patient
{
    [Key]
    public string Cpr { get; set; }         //ID
    private string _firstname;
    private string _lastname;

    //public List<TestReceving> TestHandelings { get; set; }

    public string Firstname
    {
        get { return _firstname; }
        set { _firstname = value; }
    }

    public string Lastname
    {
        get { return _lastname; }
        set { _lastname = value; }
    }
    public override bool Equals(object obj)
    {
        return obj is Patient ? Cpr == (obj as Patient).Cpr : false;
    }
}

JS:

function savePatient() {
    var Patient = {
        Cpr: $("#cpr").val(),
        Lastname: $("#lastname").val(),
        Firstname: $("#firstname").val()
    };

    var dataToPost = JSON.stringify(Patient);

    $.ajax({
        type: "POST",
        url: "/Patient/CreatePatient",
        contentType: "application/json; charset=utf-8",
        data: dataToPost,
        dataType: "json",
        success: function () {
            // do what you want on success.
            alert("saved");
        },
        error: function () {
            alert("error");
        }
    });
}

我已将其更改为:

public JsonResult CreatePatient(Patient patient)
{
    if (db.Patients.Contains(patient))
    {
        db.Patients.Remove(patient);
    }
    db.Patients.Add(patient);

    return new JsonResult();
}

function savePatient() {
    var Patient = {
        Cpr: $("#cpr").val(),
        Lastname: $("#lastname").val(),
        Firstname: $("#firstname").val()
    };

    $.ajax({
        type: "POST",
        url: "/Patient/CreatePatient",
        contentType: "application/json; charset=utf-8",
        data: Patient,
        dataType: "json",
        success: function () {
            // do what you want on success.
            alert("saved");
        },
        error: function () {
            alert("error");
        }
    });
}

但我仍然收到错误。

2 个答案:

答案 0 :(得分:2)

您不需要JSON.stringify,只需按原样发送Patient

data: Patient,

并接受行动:

public JsonResult CreatePatient(Patient patient)
{
    ...
}

更新:,但不应使用发送原始json(未经过字符串化)contentType: "application/json"

答案 1 :(得分:0)

在方法体上添加[HttpPost]属性,如

[HttpPost]
public JsonResult CreatePatient(Patient patient){...}