0

我尝试将参数接收的 int 变量与 DB 中的 int 字段进行比较。

控制器中的功能:

[AcceptVerbs(HttpVerbs.Get)]
    public JsonResult getServicoID(string serie, int numDoc)
    {
        try
        {
            var result = db.Servicos.Where(dados => dados.DadosComerciais.Serie == serie && dados.DadosComerciais.NumDoc == numDoc); // i think the problem is here - dados.DadosComerciais.NumDoc == numDoc
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new { Result = "ERROR", Message = ex.Message }, JsonRequestBehavior.AllowGet);
        }
    }

函数js:

function AddServContratado() {
//Buscar ServicoID da tabela servicos para guardar na ServicoContratado

$.getJSON("/Contrato/getServicoID", { serie: $("#Serie").val(), numDoc: $("#NumDoc").val() },
      function (result) {
          var servicoID = result.ServicosID;
          alert(result.ServicosID);
      });
4

2 回答 2

1

我找到了解决方案:

控制器:

[AcceptVerbs(HttpVerbs.Get)]
    public JsonResult getServicoID(string serie, int numDoc)
    {
        try
        {
            var result = db.Servicos.FirstOrDefault(dados => dados.DadosComerciais.Serie == serie && dados.DadosComerciais.NumDoc == numDoc);

            return Json(result.ServicosID, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new { Result = "ERROR", Message = ex.Message }, JsonRequestBehavior.AllowGet);
        }
    }

JS:

    $.getJSON("/Contrato/getServicoID", { serie: $("#Serie").val(), numDoc: $("#NumDoc").val() },
      function (result) {
          var servicoID = result;
          alert(result);
      });
于 2013-11-08T12:59:22.703 回答
0

您正在从控制器操作中返回一个列表。result变量是IEnumerable<Servico>一个。

在您的 javascript 文件中,您试图使用一些result.ServicosID无法工作的属性,因为您有一个对象列表。例如,您可以像这样访问它们:result[0].ServicosID.

如果您想访问单个对象,请确保您从控制器操作中返回了单个对象:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetServicoID(string serie, int numDoc)
{
    try
    {
        var result = db.Servicos.FirstOrDefault(dados => dados.DadosComerciais.Serie == serie && dados.DadosComerciais.NumDoc == numDoc);
        if (result == null)
        {
            // no object found in the database that matches the criteria => 404
            return HttpNotFound();
        }
        return Json(result, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        Response.StatusCode = 500;
        return Json(new { Result = "ERROR", Message = ex.Message }, JsonRequestBehavior.AllowGet);
    }
}
于 2013-11-08T12:35:48.830 回答