如何在发送POST请求后在同一个MVC视图上显示HttpResponseMessage?

时间:2014-03-27 19:08:41

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

我有一个简单的.net MVC应用程序,它从我的视图中获取firstname和lastname,并向创建用户的web api提交POST请求,并将响应发送回HttpResponseMessage。

当我提供firstname和lastname并命中时,在POST中提交api接收请求并执行其逻辑,然后返回HttpResponseMessage并返回我的响应(在本例中为“Successfully created user account”text).Content with string and response.status 。现在在我提交后的浏览器上,我离开了我所看到的视图,我看到了带有response.Content字符串的空白页面。

我想要做的是采取响应并将其显示在我所在的同一视图上。关于如何做到这一点的任何想法?

My controller
Controllers/HomeController.cs
public class HomeController : Controller
{
  public ActionResult Index()
        {
            return View();
        }
}

Razor View content
Views/Home/Index.cshtml

        <form name="createtestuserinput" action="api/createuser" method="POST">
            FirstName
            <input type="text" id="firstname" name="firstname">
            Lastname
            <input type="text" id="lastname" name="lastname">
            <input type="submit" id="createAccount" value="Create Account" />
        </form>

Web Api snippet
    public class Createuser : ApiController
    {
           public HttpResponseMessage Post(HttpRequestMessage request)
            {
               var response = new HttpResponseMessage();
              //some logic happens here
              response.Content = new StringContent("Successfully created user account");
               response.StatusCode = HttpStatusCode.OK;
             return response;
             }
    }

1 个答案:

答案 0 :(得分:1)

如果你没有理由创建一个ApiController,这就是它在MVC中的一般工作方式:

在你的HomeController中:

[HttpPost]
public ActionResult CreateUser(string firstname, string lastname)
{
    // some logic here... 
    ViewBag.Message = "Successfully created user account";
    return View("Index");
}

在Views / Home / Index.cshtml中

    <form name="createtestuserinput" action="CreateUser" method="POST">
        FirstName
        <input type="text" id="firstname" name="firstname">
        Lastname
        <input type="text" id="lastname" name="lastname">
        <input type="submit" id="createAccount" value="Create Account" />

        @ViewBag.Message
    </form>

更新: 以下代码应该可以提交到您的web api请求:

<form id="createtestuserinput">
    FirstName
    <input type="text" id="firstname" name="firstname">
    Lastname
    <input type="text" id="lastname" name="lastname">
    <input type="submit" id="createAccount" value="Create Account" />

    <div id="message"></div>
</form>

<script src="/Scripts/jquery-1.8.3.js"></script>
<script type="text/javascript">
    $(function () {
        $("#createtestuserinput").submit(function () {
            var options = {
                url: "/api/createuser",
                type: "POST",
                data: $('#createtestuserinput').serialize()
            };

            $.ajax(options).done(function (data) {
                $("#message").html(data);
            });

            return false;
        });
    });
</script>