Arnab
Arnab

Reputation: 2354

Converting a asp.net mvc webapi method to asp.net mvc method

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...

Upvotes: 0

Views: 55

Answers (1)

Bellash
Bellash

Reputation: 8184

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

Upvotes: 1

Related Questions