将asp.net mvc webapi方法转换为asp.net mvc方法

时间:2015-03-26 06:19:35

标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-mvc-5

我在web api控制器中有一个web api方法,如下所示,它工作正常。

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

我想在我的asp.net mvc控制器中使用类似的..

我尝试了以下内容..

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

发布的数据是从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") }
    });

但是,由于MVC没有[FromBody]标签,我无法访问正在发送的内容..虽然正在调用该方法,但id始终显示为null ...

1 个答案:

答案 0 :(得分:1)

试试这个

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

并在ajax帖子中更改你的网址(用你的控制器名称替换api:put" home"例如你在家庭控制器下面)

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