Asp.Net core MVC Javascript Ajax parameters null HttpPost - javascript

I am writing a javascript function for a button
<button type="button" class="btn btn-sm btn-outline-secondary" id="stopProcess" onclick="stopProcess(event, #queue.AgentQueueId, #queue.AgentId)" data-toggle="tooltip">Stop</button>
This is what my javascript function looks like
<script type="text/javascript">
$(document).ready(function () {
setInterval(function () {
reloadPage()
}, 50000);
});
function reloadPage() {
window.location.reload(true);
}
function stopProcess(e, agentQueueId, agentId) {
e.stopPropagation();
var data = JSON.stringify({ 'agentQueueId': agentQueueId, 'agentId': agentId });
$.ajax({
type: "POST",
url: "#Url.Action("StopTest", "Agents")",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
reloadPage();
},
error: function (data) {
$(".alert").text("Error completing the request.");
$(".alert").prop("hidden", false);
}
});
};
</script>
It correctly navigates to the function StopTest in my Agents controller but the parameters passed to it are null.
My controller code is
[HttpPost]
public bool StopTest(long agentQueueId, long agentId)
{
StopTestsResponse response = new StopTestsResponse();
try
{
response = _testAgentRepository.StopTest(new StopTestsRequest()
{
AgentId = agentId,
AgentQueueId = agentQueueId
});
}
catch (Exception ex)
{
throw ex;
}
return response.Success;
}
It would be of great help if anyone could point out where I am going wrong.

You should create a class with two properties:
public class Test
{
public long AgentQueueId { get; set; }
public long AgentId { get; set; }
}
And then in your controller you should have action signature like this:
public bool StopTest([FromBody]Test data)
You can see more about model binding in asp.net core here:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1

Related

Ajax POST an object with javascript, but the value in backend is null, why?

So on button click there is a function sendEmail(). Alert is working fine, I can see my datas there. But on backend I can't see anything, just everything is null.
function sendEmail() {
var datas = new Object();
datas.mail = $('#contactDropdownList').val();
datas.mailobject = $('#emailObject').val();
datas.text = $('#emailText').val();enter code here
alert(datas.mail + datas.mailobject + datas.text);
$.ajax({
type: "POST",
dataType: "json",
url: "/Email/sendEmail",
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ items: datas }),
success: function (data) {
console.log(data);
//do something with data
},
error: function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
}
});
}
C# code:
public class MyClass
{
public string Email { get; set; }
public string Object { get; set; }
public string Text { get; set; }
}
[HttpPost]
public IActionResult sendEmail(MyClass items)
{
return Json(new { data="Ok" });
}
items.Email, items.Object and items.Text are null.
And the return valu is null as well, because in javascript success: function (data) { console.log(data);
is empty string.
What can be the problem? Thank you!
Model binder expects json content to match C# class. Your datas object should look like that
var datas = {
email: $('#contactDropdownList').val(),
object: $('#emailObject').val(),
text: $('#emailText').val()
}
Since you wrapped your object ({ items: datas }), you may think it will be mapped to sendEmail(MyClass items), but in reality items name does not matter, you can change variable name to any other name you like
Make sure you apply [FromBody] attribute to your parameter like that
[HttpPost]
public IActionResult sendEmail([FromBody]MyClass items)
Complete demo:
<script>
function sendSmth() {
var data = {
Email: 'email',
Object: 'object',
Text: 'text'
};
$.ajax({
type: "POST",
dataType: "json",
url: "/home/index",
contentType: "application/json",
data: JSON.stringify(data),
success: function (datas) {
console.log(datas)
}
})
}
</script>
And controller
[HttpPost]
public IActionResult Index([FromBody]MyClass obj)
{
return View();
}
As someone has noted, you have a mismatch between what you're sending to the controller and what the model the modelbinder is expecting. You can also vastly simply your AJAX code:
function sendEmail() {
var data = {
Email: $('#contactDropdownList').val(),
Object: $('#emailObject').val(),
Text: $('#emailText').val()
};
$.post("/Email/sendEmail", data)
.done(function (response) {
console.log(response);
//do something with response
})
.fail(function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
});
}
You don't really need to specify the content type or data type - the $.post helper's defaults work just fine for what you've shown.

calling a c# class method from html page

Can we call a C# method in a class from a html page??
I have a class names Crud.cs
public class Crud
{
public String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
I want to call this method from a html page.I'm using a html page not a asp page.Is there any possibility to call without using ajax or if ajax also how could I call.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-3.2.1.js" type="text/javascript"></script>
</head>
<body>
<div style="align-content:center;">
<input type="text" id="HtmlName" />
<button id="btn_gen_html" onclick="createHtml()">Generate</button>
</div>
<div id="Msg"></div>
<div id="feedbackMsg"></div>
<script>
function createHtml() {
var name = document.getElementById("HtmlName").value;
$.ajax({
type: "POST",
url: "Crud.cs/generateFiles",
data: { name } ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else(val==1)
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
}
</script>
</body>
</html>
This is my code. Here I am not able to call generateFiles() method in crud class. Can I call so.And if I can How?
You can't call normal method. The method must be static and web method.
Try this:
public class Crud
{
[WebMethod]
public static String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
You are missing a controler in your project.
You try to retrieve data from a cs file without a controler (or a [WebMethod])? this is impossible.
Try looking for some MVC guides, Here is one from microsoft web site
You dont have to use all that ASP component that showen there, but you can see there how to retrieve data from the server to the client.
Basic syntax
<script type="text/javascript"> //Default.aspx
function myfunction() {
$.ajax({
type: "POST",
url: 'Default.aspx/myfunction',
data: "mystring",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
Default.aspx.cs
[WebMethod]
public static String myfunction(string name)
{
return "Your String"
}
If you want to use page call without ajax: Ref
//cs file (code behind)
[ScriptMethod, WebMethod]
public static string GetLabelText(string param1)
{
return "Hello";
}
//aspx page
<script type="text/javascript">
function InsertLabelData() {
PageMethods.GetLabelText(param1,onSuccess, onFailure);
}
function onSuccess(result) {
var lbl = document.getElementById(‘lbl’);
lbl.innerHTML = result;
}
function onFailure(error) {
alert(error);
}
InsertLabelData();
</script>
If you're using ASP.NET Web Forms, there is a WebMethodAttribute you can use instead of calling .cs file directly which unsupported by AJAX due to no URL routing enabled for normal classes. The web method must be declared as static:
// if you're using ASMX web service, change to this class declaration:
// public class Crud : System.Web.Services.WebService
public class Crud : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static String generateFiles(String name)
{
return generateHtml(name);
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
Then your AJAX call URL should be changed to this (note that the web method should be exist in code-behind file, e.g. Crud.aspx.cs or Crud.asmx.cs):
$.ajax({
type: "POST",
url: "Crud.aspx/generateFiles", // web service uses .asmx instead of .aspx
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
If ASP.NET MVC is used, use JsonResult to return JSON string as success result:
public class CrudController : Controller
{
[HttpPost]
public JsonResult generateFiles(String name)
{
return Json(generateHtml(name));
}
}
The AJAX call for the action method looks similar but the URL part is slightly different:
$.ajax({
type: "POST",
url: "Crud/generateFiles",
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
//Perfect solution
var params = { param1: value, param2: value2}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../aspxPage.aspx/methodName',
data: JSON.stringify(params),
datatype: 'json',
success: function (data) {
var MethodReturnValue = data.d
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
}
});
//PLEASE menntion [WebMethod] attribute on your method.

Calling controller with ajax in mvc

I'm trying to fetch data from a controller and update my view using ajax.
This is my controller:
public class PatientController
{
DatabaseContext db = new DatabaseContext();
public JsonResult GetPatientFromCpr()
{
var patient = db.Patients.FirstOrDefault(p => p.Cpr == "2410911615");
return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
And this is my ajax call:
function getPatient() {
cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
$.ajax(
{
url: '/Patient/GetPatientFromCpr',
dataType: 'json',
success: function () {
alert("success");
},
error: function () {
alert("error");
},
});
}
When i call the function i always get the error alert.
GET http://localhost:51140/Patient/GetPatientFromCpr 404 (Not Found)
Can someone point out what's wrong?
(EDIT)
I now get a new error after adding ": Controller"
GET http://localhost:51140/Patient/GetPatientFromCpr 500 (Internal Server Error)
Your 'PatientController' is not a Controller (it does not inherit from Controller)
public class PatientController : Controller
{
....
}
Inherit you PatientController with Base Controller Class
public class PatientController : Controller
In controller
public JsonResult GetPatientFromCpr()
{
var patient = db.Patients.where(p => p.Cpr == "2410911615").FirstOrDefault();
return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
And Specify the type of ajax calling
type: "POST" or type: "GET" ....
This will help you to fix error
Try using this, may be this works..!!
View:
function getPatient() {
cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
$.ajax(
{
url: '/Patient/GetPatientFromCpr',
//dataType: 'json',
type:"POST", // GET or POST
success: function () {
alert("success");
},
error: function () {
alert("error");
},
});
}
Controller:
public class PatientController : Controller
{
....
}

Trouble sending an array to a model in MVC

What I have:
A Model like this:
public class ProductModel
{
public string ProductName { get; set; }
public List<string> SkipUpdates { get; set; }
}
A controller method like this:
public ActionResult GetProductUpdates(ProductModel productModel)
{
return View("AddEdit");
}
Not doing anything for now just want to make sure that data from JS comes in correctly.
The JS:
function productModel() {
this.productName = "";
this.SkipUpdates = [];
}
Filling the model and AJAX:
var newProductModel = new productModel();
var options = $('#AdditionalSkipDates option');
var skipDates = [];
options.each(function (i, option) {
skipDates[i] = $(option).text();
});
newProductModel.productName = "ABC";
newProductModel.SkipUpdates = skipDates;
$.ajax({
type: "GET",
url: urlToGetProductSchedule,
data: newProductModel,
dataType: "json"
}).success(function () {
}).fail(function (xhr) {
alert("Something went wrong!!!");
console.log(xhr.responseText);
});
AdditonalSkip dates is a listbox with a bunch of dates in it.
What's happening:
The SkipUpdates array does have values which I can see in the browser's console.
Put a breakpoint in the controller and it hits the method.
The SkipUpdates value is null.
What's not happening:
How do I get the array to come-into the controller?
Thanks in advance.
Try to stringify the object before sending it:
$.ajax({
type: "GET",
url: urlToGetProductSchedule,
data: JSON.stringify(newProductModel),
dataType: "json"
}).success(function () {
}).fail(function (xhr) {
alert("Something went wrong!!!");
console.log(xhr.responseText);
});

Problems updating database with Jquery.Ajax

I am working on a website and would like to be able to update a field on a database table when a div is clicked. I found some example code right here on stack but for some reason it won't work, even though it was accepted. I am using C# ASP.NET MVC Razor.
My JavaScript function is as follows:
function toggleContent(id, instID) {
var doc = document.getElementsByClassName("messageContent")[id];
$(doc).slideToggle();
$.ajax({
type: 'POST',
url: "#Url.Content('/Messages/MarkSeen/')",
data: {
instanceID : instID
},
dataType: 'json'
});
}
And my JsonResult is as follows:
[HttpPost]
public JsonResult MarkSeen(int instanceID)
{
var markSeen = db.MessageInstances.First(mi => mi.MessageInstanceId == instanceID);
if (markSeen.RegisteredPerson.PersonId == CurrentUser.PersonId)
{
markSeen.Seen = true;
db.SaveChanges();
return Json(true);
}
return Json(false);
}
I'm not sure where your code fails, so I posted complete working code
If you are using the ApiController, please try the following updates to make your code works:
1. add route to WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
2. javascript
$.ajax({
type: "POST",
url: "#Url.Content("/api/lab/MarkSeen")",
data: { "instanceID": instID },
dataType: 'json',
success: function (data) { alert(data)},
error: function () { alert('error'); }
});
3. Add model to match the json from ajax request:
public class labModel
{
public int instanceID { get; set; }
}
4. Controller:
[System.Web.Mvc.HttpPost]
public JsonResult<bool> MarkSeen(labModel data)
{
return Json(true);
}

Categories

Resources