如何将 int 与 int 模型 json 和 mvc 4 进行比较



我尝试将参数接收的 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);
      });

我找到了解决方案:

控制器:

[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);
      });

您正在从控制器操作返回一个列表。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);
    }
}

最新更新