简体   繁体   English

在MVC视图中使用参数从jquery调用Web API

[英]Call web api from jquery with parameters in mvc view

I am trying to call my newly created Web API to post a message but it does not work. 我正在尝试调用新创建的Web API来发布消息,但是它不起作用。 I have a view that receives the data from controller action method. 我有一个从控制器动作方法接收数据的视图。 I am very new in creating web api and calling it from Ajax method so I am looking for good detailed instructions. 我是创建Web api并从Ajax方法调用它的新手,所以我正在寻找良好的详细说明。 I would like to pass message typed in by user in text area and also the message ID that I have added as an data attribute on button. 我想传递用户在文本区域中键入的消息,以及我作为按钮的数据属性添加的消息ID。

I have created a form and added a text area with button for user to send message. 我创建了一个表单,并添加了一个带有按钮的文本区域,供用户发送消息。 In the API, I would like to add it to database. 在API中,我想将其添加到数据库中。 I can do the database part but I would like the form to be updated once ajax call is done. 我可以做数据库部分,但是我希望一旦ajax调用完成后就可以更新表单。

View code 查看代码

 <div class="bg-dark rounded padding-x4">
            @*This form will be used to send messages. Use Jquery to run Api to send messages*@
            <form>
                <textarea placeholder="Send a new message..." id="messageToBeSent" rows="6" cols="100"></textarea>
                <button data-message-id="@Model.Messages.MessageID" class="btn btn-primary" id="sendMessage">Send Message</button>
            </form>
        </div>

My Web Api structure 我的Web Api结构

[HttpPost]
        public IHttpActionResult SendMessages(int MessageID,string MessageReply)
        {
            //Add a message to MessageReply table

            return Ok();
        }

Jquery code jQuery代码

 <script>
        $(document).ready(function () {
            $("#sendMessage").on("click", function (e) {
                e.preventDefault();
                var MessageReplyParam = $('#messageToBeSent').val();
                var button = $(this);
                $.ajax({
                    //url: "/api/messages/SendMessages?MessageID=" + button.attr("data-message-id"),
                    url: "/api/messages/SendMessages",
                    method: "POST",
                    data:{
                        MessageID:button.data("message-id"),
                        MessageReply:MessageReplyParam
                    },
                    success: function (data) {
                    }
                });      
             });
        });

    </script>

Currently, it is not hitting my API class and on Network tab in google chrome it says 404 Not found. 目前,它没有达到我的API类,并且在Google Chrome中的“网络”标签上显示“ 404 Not found”。 What am I doing wrong? 我究竟做错了什么?

Your controller action is expecting a POST request, but you're trying to send a "SendMessages" request, which is not a valid HTTP verb. 您的控制器操作正在等待POST请求,但是您正在尝试发送“ SendMessages”请求,该请求不是有效的HTTP动词。 Specify POST in the options: 在选项中指定POST:

$.ajax({
    url: "/api/messages/" + button.attr("data-message-id"),
    method: "POST",
    success: function (data) {

    }
});

You can also use .data() to better get your data-* attribute value: 您还可以使用.data()更好地获取data- *属性值:

$.ajax({
    url: "/api/messages/" + button.data("message-id"),
    method: "POST",
    success: function (data) {

    }
});

Also, is your URL correct in the first place? 另外,您的URL首先是否正确? Shouldn't it include the action name? 它不应该包含动作名称吗? And are your routes set up to automatically populate MessageID, or do you need to set it manually?: 并且您的路由是否设置为自动填充MessageID,还是需要手动设置?

$.ajax({
    url: "/api/messages/SendMessage?MessageID" + button.data("message-id"),
    method: "POST",
    success: function (data) {

    }
});

If you want, you can also use a server-side helper to generate your URL. 如果需要,还可以使用服务器端帮助程序来生成URL。 Since it's a POST request you can put the values in the request instead of on the URL. 由于这是POST请求,因此您可以将值放在请求中而不是URL上。 Something like this: 像这样:

$.ajax({
    url: "/api/messages/SendMessage",
    method: "POST",
    data: {
        MessageID: button.data("message-id")
    },
    success: function (data) {

    }
});

That way you can easily add as many properties to that data object as you like. 这样,您可以根据需要轻松地向该data对象添加尽可能多的属性。

Edit: It's possible that you may run into model binding issues here though, and it may depend on the version of Web API. 编辑:这有可能是你可能会遇到模型绑定的问题在这里虽然,这可能取决于网络API的版本。 (I'm honestly not certain.) But sometimes it sees that JavaScript object as one parameter with properties, not as separate parameters. (坦率地说,我不确定。)但有时,它会将JavaScript对象视为具有属性的一个参数,而不是作为单独的参数。

In that case, create a server-side model: 在这种情况下,请创建服务器端模型:

public class Message
{
    public int MessageID { get; set; }
    public string MessageReply { get; set; }
}

And use it on the action method: 并在action方法上使用它:

public IHttpActionResult SendMessages([FromBody]Message message)

This should more effectively bind the incoming JSON to the method parameter. 这应该更有效地将传入的JSON绑定到method参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM