简体   繁体   中英

How to get value from jquery which come from api controller

Hello I have a web API controller which is returning an integer value and I don't know how to get it in a jquery ajax function. My API controller is following.

[HttpGet]
[Route("api/tblProducts/{UserId}/CheckUserAvil")]
[ResponseType(typeof(int))]
public IHttpActionResult CheckUserAvil(string UserId)
{
    int Exist = db.CheckUserIdAvil(UserId);
    return Ok(Exist);
}

And my jquery code is given

$.getJSON("/api/tblProducts/" + Userid + "/CheckUserAvil", function (data) {

});

I don't know how to handle response I want Exist variable value which come from controller. Please help me.

UPDATE My Stored Procedure Code is fallowing

USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[CheckUserIdAvil]    Script Date: 8/19/2018 1:18:30 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[CheckUserIdAvil]
      @UserId nvarchar(255)
AS
BEGIN
      SET NOCOUNT ON;

      DECLARE @Exists INT

      IF EXISTS(SELECT @UserId
                        FROM tblUser
                        WHERE UserId = @UserId  )
      BEGIN
            SET @Exists = 1
      END
      ELSE
      BEGIN
            SET @Exists = 0
      END

      RETURN @Exists
END
GO

And it is workin well in Sql But in Api.It is returing -1 all the time

the callback argument data will have the data you seek.

One suggestion would be to have the action return a model that makes the returned data easier to understand.

For example, the following uses an anonymous object to hold the data.

[HttpGet]
[Route("api/tblProducts/{UserId}/CheckUserAvil")]
[ResponseType(typeof(int))]
public IHttpActionResult CheckUserAvil(string UserId) {
    int exist = db.CheckUserIdAvil(UserId);
    var model = new {
        Exist = exist
    };
    return Ok(model);
}

the client will then extract the desired data from the response in the callback function

$.getJSON("/api/tblProducts/" + Userid + "/CheckUserAvil", function (data) {
    var exist = data.Exist;
    console.log("Exist: " + exist);
    //...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM