0

I have a web api method in a web api controller as below which is working perfectly..

[Route("api/myquery")]
[HttpPost]
public HttpResponseMessage MyQuery([FromBody] string id)
{
    if (string.IsNullOrEmpty(id))
    {
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }
    return new HttpResponseMessage(HttpStatusCode.OK);      
}

I would like to use a similar one in my asp.net mvc controller..

I tried the following..

[HttpPost]
public ActionResult MyQuery(string id)
{      
    return this.Content("");
}

The data posted is sent from a same method in javascript.

$.ajax("/api/myquery", {
        data: JSON.stringify(tmp1),
        type: "post", contentType: "application/json",
        success: function (result) { alert("Saved Successfully") },
        error: function (result) { alert("Error Saving") }
    });

But, as MVC does not have a [FromBody] tag I'm unable to access the content being sent.. though the method is being called, id always shows null...

4
  • Assuming tmp1 is { id: someValue } then you need to specify the correct url - url: '/yourControllerName/myquery', or better url: '@Url.Action("myquery", "yourControllerName")', Commented Mar 26, 2015 at 6:46
  • The method is being accessed meaning the cursor reaches inside the method on debug but id is always null Commented Mar 26, 2015 at 6:52
  • 1
    Are you sure the value of tmp1 is { id: someValue }? Commented Mar 26, 2015 at 7:01
  • the key was { id: someValue } only tmp did not have id which is why id was coming null, tx.. Commented Mar 26, 2015 at 7:02

1 Answer 1

1

try this

      [HttpPost]
      public ActionResult MyQuery(string id)
      {
          if (string.IsNullOrEmpty(id))
          {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
          }
          return Json("message","text/json",JsonRequestBehavior.AllowGet);      
      }

and change your url in ajax post (replace api by your controller name: put "home" if you are under home controller for example)

$.ajax("home/myquery", {
    /*data: JSON.stringify(tmp1),*/
    data:  JSON.stringify({id:tmp1}),
    type: "post", contentType: "application/json",
    success: function (result) { alert("Saved Successfully") },
    error: function (result) { alert("Error Saving") }
    });
Sign up to request clarification or add additional context in comments.

Comments

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.