calling a c# class method from html page - javascript

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.

Related

What's the correct way to create class in JavaScript and pass that to MVC controller

I have a complex form with different tabs, so my ask is to save the entire form data to database on final save. I have the models as per my database as follows, posting sample class
public class VesselDetail
{
public string VesselName { get; set; }
}
public class MainModel
{
public VesselDetail VesselDetail { get; set; }
}
I have created JavaScript models as follows
class VesselDetail {
constructor() {
}
VesselName;
}
class MainModel {
constructor() {
this.VesselDetail = [];
}
}
On my save I am framing the data as follows
let data = new MainModel();
let vesselDetail = new VesselDetail();
vesselDetail.VesselName = "XYZ";
data.VesselDetail.push(vesselDetail);
$.ajax({
url: '/Controller/SaveFormData',
type: 'POST',
data: '{mainModel: ' + JSON.stringify(data) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
},
error: function (request) {
hideSpinner();
}
});
My controller is as follows
[HttpPost]
public JsonResult PostUserData(MainModel mainModel)
{
return new JsonResult { Data = "OK" };
}
Somehow I am unable to see the vessel name that was given. I would like to know are my JavaScript models are correct or should I do any changes? Any better idea to make these models in JavaScript.
Don't hand-construct JSON, it's really easy to get it wrong. In this case, you haven't put the necessary " around mainModel in the JSON you're sending the server, which makes it invalid. As a result, the server won't be able to parse the JSON it receives.
$.ajax({
url: '/Controller/SaveFormData',
type: 'POST',
data: '{mainModel: ' + JSON.stringify(data) + '}',
// ^−−−−−−−−^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− missing quotes
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
},
error: function (request) {
hideSpinner();
}
});
Instead, let JSON.stringify do it for you:
$.ajax({
url: '/Controller/SaveFormData',
type: 'POST',
data: JSON.stringify({mainModel: data}),
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
},
error: function (request) {
hideSpinner();
}
});
Also, unless your server is returning JSON you're not using, you don't need dataType. (Even if it is, it should be returning the correct Content-Type header in which case dataType is redundant anyway.)
I also suggest either consistently using property declaration syntax (which is fairly new) or consistently not using it:
Not using it:
class VesselDetail {
}
class MainModel {
constructor() {
this.VesselDetail = [];
}
}
Using it:
class VesselDetail {
VesselName;
}
class MainModel {
VesselDetail = [];
}
Here's an example of the JSON that will be produced by your code with the changes above (I've used property declaration syntax — the second set of classes above — but they'll both produce the same thing):
class VesselDetail {
VesselName;
}
class MainModel {
VesselDetail = [];
}
let data = new MainModel();
let vesselDetail = new VesselDetail();
vesselDetail.VesselName = "XYZ";
data.VesselDetail.push(vesselDetail);
const json = JSON.stringify({mainModel: data});
console.log(json);
As you can see, VesselName is not blank.
try this, it was tested in VS2019 and working properly
var mainModel= { VesselDetail : { VesselName :"XYZ"} };
$.ajax({
url: '/Controller/PostUserData',
type: 'POST',
data: { mainModel: mainModel),
success: function (result) {
hideSpinner();
alert(JSON.stringify(result));
},
error: function (request) {
hideSpinner();
}
});
and fix VesselDetail class by adding setter and getter
public class VesselDetail
{
public string VesselName { get; set;}
}
And I see a bug in your action. What is a Data?
return new JsonResult { Data = "OK" };
try this
return new JsonResult(mainModel.VesselDetail.VesselName);
but if you like it a hard way you can try this
class VesselDetail {
VesselName;
}
class MainModel {
VesselDetail = {};
}
let mainModel= new MainModel();
data.VesselDetail.VesselName="XYZ";
UPDATE
Sometimes this working better, depending on net version or if you are using API controller
var mainModel= { VesselDetail : { VesselName :"XYZ"} };
$.ajax({
url: '/Controller/PostUserData',
type: 'POST',
data: JSON.stringify(mainModel),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
alert(JSON.stringify(result));
},
error: function (request) {
hideSpinner();
}
});
but you have to add [FromBody] to action
[HttpPost]
public JsonResult PostUserData([FromBody] MainModel mainModel)
{
return new JsonResult(mainModel.VesselDetail.VesselName);
}
you put the VesselName out of the builder
should be like this
class VesselDetail {
constructor() {
this.VesselName;
}
}
class MainModel {
constructor() {
this.VesselDetail = [];
}
}

Failed to load resource: the server responded with a status of 405

When trying to call an ASP.NET method from the client using $.ajax it gives the following error "Failed to load resource: the server responded with a status of 405 ()" knowing that the client and the API are both running on the same domain "localhost:4500", I followed the procedure I found in this Microsoft docs "https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-javascript?view=aspnetcore-5.0 " and added the wwwroot folder to avoid the CORS issue but still can't call the API methods through the $.ajax method in javascript.
I tested the backend code through swagger and it was working just fine.
this my backend controller code:
[ApiController]
[Route("api/[Controller]")]
public class RunAnalysisController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok();
}
[HttpPost("LoadFramesData")]
public IActionResult LoadFrameData([FromBody]RootObject ModelData)
{
try
{
ManageModel.CreateModel(ModelData);
return Ok(ModelData); //returning same object for testing purpose
}
catch
{
return BadRequest("Error");
}
}
}
and this my ajax function in the client side:
$.ajax({
type: "POST",
url: "api/RunAnalysis/LoadFramesData", ///// URL must be specified
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(new RootData()), //this class returns a json object
cache: false,
success: function (result) {
console.log(result);
},
error: function (ex) {
WriteToConsole(ex.responseText);
}
});
As mentioned in the comments, the issue relates the request url, change the url as below: url: "/api/RunAnalysis/LoadFramesData.
More detail information, you could refer the following sample:
Model:
public class RootObject
{
public int ID { get; set; }
public string Name { get; set; }
}
MVC View Page:
<input type="button" id="btnsubmit" value="Click Me" />
#section Scripts{
<script>
$(function () {
// LoadChart();
class RootData {
constructor(id, name) {
this.ID = id;
this.Name = name;
}
}
$("#btnsubmit").click(function () {
//var data = {};
//data.ID = "1001";
//data.Name = "Tom";
$.ajax({
type: "POST",
url: "/api/todo/LoadFramesData", ///// URL must be specified
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(new RootData(1001, "Tom")), //this class returns a json object
cache: false,
success: function (result) {
alert(result.name);
},
error: function (ex) {
alert(ex.responseText);
}
});
});
});
</script>
}
API upload method:
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
[HttpPost("LoadFramesData")]
public IActionResult LoadFrameData([FromBody] RootObject ModelData)
{
try
{
return Ok(ModelData);
}
catch
{
return BadRequest("Error");
}
}
The result as below:

Getting exeption when sending variable via ajax

Getting an error when trying to delete a user from db.
Here is the code that i wrote:
This is server side:
#RestController
public class EmployeeRestController {
#DeleteMapping( value = "/delete_user")
public List<Employee> deleteEmployee(#RequestParam(value = "id") Integer id) {
employeeService.deleteEmployee(id);
List<Employee> list = employeeService.getAllEmployees();
return list;
}
}
Client side:
function delete_row(id){
$.ajax({
type:'DELETE',
url:'/delete_user',
dataType: 'json',
data:JSON.stringify({
id:id
}),
success:function(data){
console.log(data);
}
});
}
Error from server side :
DefaultHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required Integer parameter 'id' is not present]
Error code from client side is 400
I am noob at ajax , javascript and spring. Sorry if the problem is obvious and thanks in advance.
did you tried this
function delete_row(id){
$.ajax({
type: "DELETE",
url: "/delete_user",
data: { id: id },
success: function (data) {
console.log(data);
},
error: function () {
}
});
}
or directly bind to url
function delete_row(id){
$.ajax({
type: "DELETE",
url: "/delete_user?id="+id,
success: function (data) {
console.log(data);
},
error: function () {
}
});
}
Try using PathVariable instead of RequestParam.
#DeleteMapping(value = "/delete_user/{id}")
public List<Employee> deleteEmployee(#PathVariable("id") Integer id) {
employeeService.deleteEmployee(id);
List<Employee> list = employeeService.getAllEmployees();
return list;
}
}

Asp.Net core MVC Javascript Ajax parameters null HttpPost

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

How to pass string value from javascript to function in ASHX

I'm used this code to pass parameter from jQuery to ASHX, actually I want to upload file using Uploadify Plugin and send Parameter named 'Id' to ASHX
function CallHandler() {
$.ajax({
url: "PIU.ashx/MyMethod",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { 'Id': '10000' },
responseType: "json",
success: OnComplete,
error: OnFail
});
return false;
}
function OnComplete(result) {
alert(result);
}
function OnFail(result) {
alert('Request Failed');
}
and this ASHX code:
public void ProcessRequest(HttpContext context)
{
var employee = Convert.ToInt32(context.Request["Id"]);
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string serEmployee = javaScriptSerializer.Serialize(employee);
context.Response.ContentType = "text/html/plain";
context.Response.Write(serEmployee);
parent MyParent = (parent)context.Session["mahdZNUparent"];
//the file data is the file that posted by Uploadify plugin
HttpPostedFile PostedFile = context.Request.Files["Filedata"];
string FileName = PostedFile.FileName; // whene i comment this line, the code works
// properly, but when uncomment this line, the code get to 'Request Failed'
}
public bool IsReusable
{
get
{
return false;
}
}
how can I Solve this problem!!!!!!!
You may want to take a loot at this: http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
And this one too: Using jQuery for AJAX with ASP.NET Webforms

Categories

Resources