控制器始终只从指定字段的json接收null

时间:2013-05-24 14:37:33

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

Hy伙计们!

首先:我在开始提问之前找到了这些帖子:questions/11344035 - questions/15939944 - questions/9412449 - questions/9162359 - questions/1551263

第二:没有一个解决了我的问题...... :(

嗯,这是我的第一个MVC4项目,我尝试按$ .ajax发送我的数据如下:

var exames = {
    "ExameId": "",
    "Valor": "", 
    "CodLab": "", 
    "Dias": "", 
    "LayoutId": ""
};
var apoio = {
    "ApoioId": "",
    "Razao": "",
    "Endereco": "",
    "Bairro": "",
    "Cidade": "",
    "Uf": "",
    "Cep": "",
    "Telefone": "",
    "Fax": "",
    "Email": "",
    "CodLab": "",
    "Obs": "",
    "Status": "",
    "ArqRotina": "",
    "ArqApoio": "",
    "Senha": "",
    "Exames": []
};

apoio.ApoioId = $("#hdApoioId").val();
apoio.Razao = $("#Razao").val();
apoio.Endereco = $("#Endereco").val();
apoio.Bairro = $("#Bairro").val();
apoio.Cidade = $("#Cidade").val();
apoio.Uf = $("#Uf").val();
apoio.Cep = $("#Cep").val();
apoio.Telefone = $("#Telefone").val();
apoio.Fax = $("#Fax").val();
apoio.Email = $("#Email").val();
apoio.CodLab = $("#CodLab").val();
apoio.Obs = $("#Obs").val();
apoio.Status = $("#Status").val();
apoio.ArqRotina = $("#ArquivoRotina").val();
apoio.ArqApoio = $("#ArquivoApoio").val();
apoio.Senha = $("#SenhaLab").val();

var tbody = document.getElementById(idTabExames).tBodies[0];
var numLinhas = tbody.rows.length;

for (var i = 0; i < numLinhas; i++) {
    exames.ExameId = tbody.rows[i].cells[0].firstChild.nodeValue.toString();
    exames.CodLab = tbody.rows[i].cells[1].firstChild.nodeValue;
    exames.Dias = tbody.rows[i].cells[2].firstChild.nodeValue;
    exames.Valor = tbody.rows[i].cells[3].firstChild.nodeValue;
    exames.LayoutId = tbody.rows[i].cells[4].firstChild.nodeValue;
    apoio.Exames.push(exames);
    exames = {
        "ExameId": "",
        "CodLab": "",
        "Dias": "",
        "Valor": "",
        "LayoutId": "",
        "ApoioId": ""
    };
}

$.ajax({
    url: '/ApoioExames/Create',
    data: JSON.stringify(apoio),
    type: 'POST',
    contentType: "application/json",
    dataType: 'json',
    processData: true,
    success: function (result) {
        if (result.Success == "1") {
            if (console.window) console.log('sucess: '+result);
            window.location.href = "/ApoioExames/Index";
        }
        else {
            alert(xhr.status);
            alert('Error: ' + xhr.responseText);
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
    }
});

应用JSON.stringfy(apoio),我得到一个有效的json返回(用http://jsonlint.com验证)但是apoio.Exames字段(只有它)在我的控制器上为空。总是!

[HttpPost]
public JsonResult Create(ApoioModel apoio)
{
    try
    {
        if (ModelState.IsValid)
        {
            if (apoio.Id > 0)
            {
                var exames = db.DbApoioExames.Where(p => p.ApoioId == apoio.Id);
                foreach (ApoioExmModel exm in exames)
                    db.DbApoioExames.Remove(exm);
                foreach (ApoioExmModel exm in exames)
                    db.DbApoioExames.Add(exm);
                db.Entry(apoio).State = EntityState.Modified;
            }
            else
            {
                db.DbApoio.Add(apoio);
            }
            db.SaveChanges();
            //If (Sucess== 1) { Salvar/Atualizar } else { Exception }
            return Json(new { Success = 1, ApoioId = apoio.Id, ex = "" }, JsonRequestBehavior.AllowGet);
        }
    }
    catch (Exception ex)
    {
        return Json(new { Success = 0, ex = ex.Message }, JsonRequestBehavior.AllowGet);
    }
    return Json(new { Success = 0, ex = new Exception("Impossível Salvar").Message }, JsonRequestBehavior.AllowGet);
} 

我的模型ApoioModel和ApoioExmModel是:

[Table(name: "apoio", Schema = "public")]
public class ApoioModel
{
    [Key, Column("id", Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Column("razao")]
    [Display(Name = "Razão Social")]
    [DataType(DataType.Html)]
    [Required(ErrorMessage = "A razão social deve ser informada")]
    public string Razao { get; set; }

    [Display(Name = "Endereço")]
    [Column("endereco")]
    public string Endereco { get; set; }

    [Display(Name = "Bairro")]
    [Column("bairro")]
    public string Bairro { get; set; }

    [Display(Name = "Cidade")]
    [Column("cidade")]
    public string Cidade { get; set; }

    [Display(Name = "CEP")]
    [Column("cep")]
    public string Cep { get; set; }

    [Display(Name = "UF")]
    [Column("uf")]
    [StringLength(2)]
    public string Uf { get; set; }

    [Display(Name = "Status")]
    [Range(0, 1), Column("status")]
    public int Status { get; set; }

    public virtual ICollection<ApoioExmModel> ApoiosExm { get; set; }

}

Table(name: "apoioexm", Schema = "public")]
public class ApoioExmModel
{
    [Key, Column("id")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int? Id { get; set; }

    [Column("exame_id")]
    public int ExameId { get; set; }

    [Column("apoio_id")]
    public int ApoioId { get; set; }

    [Column("valor")]
    public float Valor { get; set; }

    [Column("codlab")]
    public string CodLab { get; set; }

    [Column("dias")]
    public float Dias { get; set; }

    [Column("layout_id")]
    public int LayoutId { get; set; }

    [ForeignKey("ApoioId")]
    public virtual ApoioModel Apoios { get; set; }
}

我正在尝试创建一个CRUD主/细节。我使用的是Postgre,而不是SQL Server,但这不是问题所在。

当我在Chrome中调试时,我认为数据传输正常!

Request U R L : h t t p : / / l o c a l h o s t:9795/ApoioExames/Create
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Content-Type:application/json
Origin:h t t p : / / localhost:9795
Referer: h t t p : / / localhost:9795/ApoioExames/Create
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
X-Requested-With:XMLHttpRequest
Request Payload
{Razao:kkkkkkk, Endereco:kkkkkkkkk, Bairro:kkkkkk, Cidade:kkkk, Uf:kk, Cep:12341234,…}
Bairro: "kkkkkk"
Cep: "12341234"
Cidade: "kkkk"
Endereco: "kkkkkkkkk"
Exames: [{ExameId:1252, Valor:1, CodLab:1, Dias:1, LayoutId:1826},…]
0: {ExameId:1252, Valor:1, CodLab:1, Dias:1, LayoutId:1826}
1: {ExameId:1252, CodLab:1, Dias:1, Valor:1, LayoutId:1826, ApoioId:}
Razao: "kkkkkkk"
Uf: "kk"
有人帮帮我吗? 对不起,我的英文不好,帖子很大! 谢谢!

1 个答案:

答案 0 :(得分:1)

我有两件事。

  1. ApoiosExm应命名为Exames,反之亦然
  2. 我不确定它是否可以映射到ICollection<ApoioExmModel>。无论哪种方式,如果你问我,我建议不要直接映射到你的实体类。