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

时间:2013-11-08 12:32:20

标签: javascript jquery json asp.net-mvc

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

2 个答案:

答案 0 :(得分: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);
      });

答案 1 :(得分: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);
    }
}