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

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

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

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

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

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.

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