I am trying to call my newly created Web API to post a message but it does not work. 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. 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.
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. I can do the database part but I would like the form to be updated once ajax call is done.
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
[HttpPost]
public IHttpActionResult SendMessages(int MessageID,string MessageReply)
{
//Add a message to MessageReply table
return Ok();
}
Jquery code
<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. What am I doing wrong?
<span data-url="@Url.Action("SendMessages", "messages", new {/*Route values here*/)">more info: learn.microsoft.com/en-us/dotnet/api/… An example: stick this in the<form>element