How to fire mailto urls from action method - javascript

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');
}
});
}

Related

The GET request call returns wrong result

I would like to call my WEB API in .NET Core from the jQuery like below:
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
JsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
return Json(welCome, JsonSettings);
}
catch(Exception ex)
{
throw ex;
}
}
And the jQuery caller:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "http://localhost:5000/api/mycontroller/GetText?callback=?",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
if (data.success) {
alert('Success -> ' + JSON.stringify(data.statusText));
}
},
error: function (data) {
alert('Error -> ' + JSON.stringify(data.statusText));
}
});
});
</script>
The API is calling successfully but it seems it will then redirect to error function in my Ajax and show the error alert with a "success" as it's statusText. I mean this: Error -> "Success" I am not sure why this happens?
I would like to print welCome as a success result and in the alert command.
Also please note that I am calling this API from another project, I mean the jQuery's AJAX code is inside another project. I am not sure if it is important or not at all.
The jQuery's AJAX Caller path: file:///C:/Users/Me/Desktop/Path/index.html
The API's address: C:\Users\Me\Documents\Visual Studio 2017\Projects\ThisProject\MyAPI
And the URL of this API: url: "http://localhost:5000/api/mycontroller/GetText",
Try the C# Code in the following manner :
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
return Ok(new { message = welCome });
}
catch(Exception ex)
{
throw ex;
}
}
Try the Jquery Code in the following manner :
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'GET',
url: 'http://localhost:5000/api/mycontroller/GetText',
success: function (response) {
alert('Success' + response.message);
},
failure: function (response) {
}
});

How to send a JavaScript object on the server side (ASP NET MVC)?

Below is the relevant code (JS+jQuery on the client side):
function getuser(username, password) {
var user = new Object();
user.constructor();
user.username = username;
user.password = password;
//....
$("#a1").click(function () {
var u = getuser($("#username").val(), $("#password").val());
if (u == false) {
alert("error");
} else {
//....
}
});
}
The question is how to send var u to a session on the server side?
You can use ajax to accomplish this. Something like:
$.ajax({
url: "/Controller/Action/",
data: {
u: u
},
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
//handle response from server
}
});
Then have a controller action to receive the data:
[HttpPost]
public ActionResult Action(string u)
{
try
{
//do work
}
catch (Exception ex)
{
//handle exceptions
}
}
Note that /controller/action will be specific to where youre posting the data to in your project
See the documentation
For example:
If you just want to do a simple post the following may suit your needs:
var user = getUser(username, password);
$.post(yourserverurl, user, function(response){console.log("iam a response from the server")});
As the documentation says:
This is a shorthand to the equivalent Ajax function:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
So In your example:
$.ajax({
type: "POST",
url: "/mycontroller/myaction",
data: {user: getUser(username, password)},
success: function(responseFromServer){//handleResponseHere},
error: function(xhr){//handleyourerrorsHere}
dataType: yourdatatype
});

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

How to send HTML content to ASP.NET MVC JSON function?

This is my jQuery code
and the next is my json function to hanlde this jquery code that named InsertMatlabJson.
The problem is no text comes in to the .NET json function. . .
function insert() {
var url = '<%=Url.Content("~/") %>' + "Matlab/InsertMatlabJson";
var text = document.getElementById('MainContent_FreeTextBox1').value
$.ajax({
url: url,
type: 'GET',
data: { text: text},
contentType: 'application/json; charset=utf-8',
success: function (response) {
//your success code
alert("opk");
},
error: function () {
//your error code
alert("no");
}
});
}
and this is my Json function in ASP.NET MVC
public JsonResult InsertMatlabJson(string text)
{
}
This should do it
[AllowHtml]
public JsonResult InsertMatlabJson(string text)
{
}

C# Web method is not calling in javascript

i create a web method and now i'm calling this in my java script file but it give an path error,it is not able to find path what i'm giving ..
Web method code is :
[System.Web.Services.WebMethod]
public static int ItemCount(string itemId)
{
int val = 0;
Item itm = Sitecore.Context.Database.GetItem(itemId);
val = itm.Children.Count;
return val;
}
java script function calling like as:
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Views/GetItem.aspx/ItemCount",
data: { itemId: itemId },
dataType: "json",
async: false,
success: function (data) {
funRes = data.result;
},
error: function(err) {
alert(err.responseText);
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;}
while i'm giving exact path for the C# method class but it's not working give an error on console, can anyone suggest me what i'm missing here..
There are few rules for ajax to work with asp.net.
Your WebMethod should be public and static.
If your WebMethod expects some parameter(s) than these parameter(s) must be passed as data in ajax.
Name of parameter(s) should be same in WebMethod and in data part of ajax.
Data passed from ajax should be in json string.For this you can use JSON.stringify or you will have to surround the values of parameter(s) in quotes.
Please check the below sample ajax call
function CallAjax()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/CallAjax",
data: JSON.stringify({ name: "Mairaj", value: "12" }),
dataType: "json",
async: false,
success: function (data) {
//your code
},
error: function (err) {
alert(err.responseText);
}
});
}
[WebMethod]
public static List<string> CallAjax(string name,int value)
{
List<string> list = new List<string>();
try
{
list.Add("Mairaj");
list.Add("Ahmad");
list.Add("Minhas");
}
catch (Exception ex)
{
}
return list;
}
EDIT
If you use GET in ajax than you need to enable your webmethod to be called from GET request. Add [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)] on top of WebMetod
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static int ItemCount()
Just Modify the javascript function as below
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
type: "GET",
url: "/Views/GetItem.aspx",
data: 'itemID=' + itemId,
contentType: "application/html",
dataType: "html",
success: function (response) {
funRes= response.result;
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;
}
I am not sure it is a solution for every question subject which web method not fire. But I discovered today when there is ' char in the string. Web Method not firing.

Categories