2

嘿伙计们!

首先:在开始我的问题之前,我已经找到了这些帖子: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"

谁来帮帮我?对不起我的英语不好和大帖子!谢谢!

4

1 回答 1

1

我有两个想法。

  1. ApoiosExm应该命名Exames,反之亦然
  2. 我不确定它是否可以映射到ICollection<ApoioExmModel>. 无论哪种方式,如果您问我,我建议不要直接映射到您的实体类。
于 2013-05-24T14:50:01.390 回答