2

I am trying to pass a single parameter (string value) to webapi controller but, it is not working. The parameter value is reaching the controller as 'null'. Here is my WebApi config,

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{action}"
           );

        }
    }

Controller:

        [HttpPost]
        public HttpResponseMessage GetDataView(string request)
        { 
            try
            {
                var result = DB.GetDataView(request);

                return Request.CreateResponse(HttpStatusCode.OK, result);
            }
            catch (Exception ex)
            {            
                //todo: log exception   
                throw ex;
            }
        }

AJAX

var serverName = 'ds100';
 $.ajax({
        url: 'api/ServerInfo/GetDataView',
        type: 'POST',
        dataType: 'json',
        data: serverName,
        success: function (data, textStatus, xhr) {

        },
        error: function (xhr, textStatus, errorThrown) {

        }

Am I missing anything? Any help is appreciated.

2
  • 1
    you can try this data: {request: serverName} at your ajax method Commented May 28, 2015 at 18:59
  • You get a an error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' Commented Jan 25, 2017 at 19:01

1 Answer 1

4

The issue seems to be on you ajax parameters the data parameter receives an object (json) that holds a property for each of the values you are passing in the request, I think you should use

 var serverName = 'ds100';
 $.ajax({
    url: 'api/ServerInfo/GetDataView',
    type: 'POST',
    dataType: 'json',
    data: {request: serverName} ,
    success: function (data, textStatus, xhr) {

    },
    error: function (xhr, textStatus, errorThrown) {

    }

and that should do it

Sign up to request clarification or add additional context in comments.

2 Comments

This worked for me but using type:GET. I am still finding out why type:POST is not working. Code is exactly the same except POST
@SachinPakale have tried not setting dataType: 'json'? I think that might be the issue, since it's a GET request all info should go in the URL and I think json implies it goes like that in the Body which GET request are not allowed to have. Hope this helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.