Pass messageID to controller? - javascript

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()
{
}

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

Related

Send Request In Laravel Using AJAX GET Method

Want to Access Show function data through AJAX, but it returns error when i passed id variable in route
Contoller
public function show($id)
{
$features['UnitFeatures'] = UnitFeatures::find($id);
return $features;
}
View Blade File
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var feature_id = $('#unitFeatures').val();
$.ajax({
url: '{{ route('unitfeatures.show',feature_id) }}', // error in this line when i pass feature_id value to route
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Please give me a solution
The problem is that you cannot access a JS variable in your {{}} PHP code.
You will have to get the route uri and replace the placeholder manually in your JS code.
You can get the URI of your Route with this piece of code:
\Route::getRoutes()->getByName('unitfeatures.show ')->uri
This returns the uri as a string like that: /sometext/{id}
Now you can simply replace the {id} with the feature_id by using str.replace() or whatever function you like.
var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
url: origUrl.replace('{id}', feature_id),
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Problem With You are using Javascript Variable in PHP Code You can use Javascript Variable After Execution of PHP Code treated as a String.
$.ajax({
url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});

Pass contents of a list box to controller in Razor

I'm very new at dealing with javascript. I have a listbox filled with IEnumerable values that I want to pass back to the controller but I'm stuck on how I would go about doing so. Any suggestions?
Try this
ASP.Net MVC How to pass data from view to controller
or try use the Jquery ajax call this way. So I'm not sure what about lis tbox is.
Javascript
$(document).ready(function () {
var listbox = $('#yourListboxID');
var formData = new FormData();
formData.append('Value', listbox[0].value);
formData.append('ID', listbox[0].id);
formData.append('OtherVariable',"..." );
$.ajax({
url: 'Ajax/Test', //url--> controller/Method
type: "POST",
dataType: 'json', // data type return form your controller
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (result) {
console.log(result); //<--- "Sucess"
},
error: function (xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
AjaxController.cs
[Route("[controller]/[action]")]
public class AjaxController : Controller
{
[HttpPost]
public JsonResult Test(string value01)
{
var ID = Request.Form["ID"].ToString();
var Value = Request.Form["Value"].ToString();
return Json("Sucess");
}
}

Submitting Ajax request from external javascript file in ASP.NET MVC

I am trying to submit an ajax request from an external JavaScript file in ASP.NET MVC. I'm getting a 500. What am I doing wrong?
Ajax call (From external JS file)
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Controller Action Method (That should be catching the request)
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpGet]
public void AjaxEndpoint()
{
var thing = 1 + 2;
}
// AJAX endpoint for GetProducts.js
[HttpPost]
public void AjaxEndpoint(string jsonData)
{
var thing = 1 + 2;
}
}
Error I'm getting
You either need to remove the contentType option
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
dataType: "json",
success: successFunc,
error: errorFunc
});
or alternatively, stringify the data
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: JSON.stringify({ jsonData: "testing" }),// modify
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Your ajax call needs to be to an ActionResult in the controller, The controller performs and returns the data to the page
[HttpPost]
public ActionResult ajaxcall(string ids)
{
String Data = code to perform
return Json(Data);
}
this is the basic idea. Javascript makes the call and uses the json data returned on the clients page

How to call this.Page (server page) from javascript

I have methos to display content of page at server side like
DisplayDetails(Page PageNema)
{
///
}
How can i call this function from javascript as well as how can i pass Page argument from Javascript
If it's WebForm you must set this method as WebMethod, so then you can call this method from jQuery. Something like that:
Client Side.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Server side:
public partial class _Default : Page
{
[WebMethod]
public static string DisplayDetails()
{
//your code to retrieve details here
return Details;
}
}
[WebMethod]
public static string DisplayDetails(parameter1,parameter2,etc...)
{
return something;
}
Client side code
<script type="text/javascript">
function functionName(callback) {
$.ajax({
type: "POST",
url: 'PageName.aspx/DisplayDetails',// your function name
data: '{"argument1","argument2",etc...}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// If u want something from serverside function then write your code here
},
error: function (e) {
}
});
}
</script >

How to fire mailto urls from action method

I am a beginner in MVC. I want to develop an action method in MVC which fires Mailto:?body=body goes here.&subject=test subject and so the default mail client will automatically populate the email for the user. Right now I have List<String> which contain mailto: urls.
Please, if you have any experience or demo code it will be helpful to me.
Thanks in advance.
try this :
window.location.href = "mailto:address#dmail.com";
with body
window.location.href = "mailto:address#dmail.com?body=yourBody";
Event with jquery
$('button').on('click', function(){
window.location.href = "mailto:address#dmail.com?body=yourBody";
});
My ActionMethod
[HttpPost]
public JsonResult emailTemplate()
{
List<String> str = new List<String>();
str.Add("Mailto:?body=Hello1&subject=test subject1");
str.Add("Mailto:?body=Hello2&subject=test subject2");
return Json(str);
}
JavaScript Function in view
function SendMailClicked() {
$.ajax({
type: "POST",
url: "/Home/emailTemplate",
//data: "{'ReviewComponentIds':'1,2,3'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
jQuery.each(response, function () {
window.location.href = this + '\n';
});
},
failure: function (errMsg) {
alert('failure');
}
});
}

Categories