Sam Sam - 1 month ago 15
Ajax Question

Pass messageID to controller?

I need to pass messageID to my controller, I am not sure how to do this please see my javascript below and controller. Also how would i do somethinglike string message ID do this if its checked etc...

$(".markmessage").click(function () {
var messageId=$(this).data("id"); //need to pass this message ID to controller.
//I need to pass the messageID to server which is CRM
$.ajax({
url: "@Url.Action("", "")", //Need to add my URl here
type: "POST",
data: JSON.stringify({messageID : messageId}), //method converts a JavaScript value to a JSON string
dataType: "json",
success: function (response) {
$(this).remove();
}
});
});


My controller method for messageID,

[HttpPost]
public ActionResult markmessage()
{

}

Answer

Just to be safe when deploying to production we need to extract the root URL. In you Layout.cshtml add this ;

<script>
        var baseUrl = "@Url.Content("~")";
</script>

In your ajax

$.ajax({
    url: baseUrl + '/Controller/Action', //Need to add my URl here
    type: "POST",
    data: {'messageID' : messageId},
    dataType: "json",
    success: function (response) {
        $(this).remove();
    }
    });
});

In controller [HttpPost]

public ActionResult markmessage(string messageID)
{
    if (messageID == "read do this")
    {
       .. Insert your logic here
    }
}

As simple as that, remember URL.Action will not work in javascript because it is for asp only