AngularJS: How to send JS object to c# controller via $http post? - javascript

Here is my code for AngularJS controller from which i am sending http post request to server:
'use strict';
var input = {title: "", note:""};
notes.controller('inputController', function inputController($scope, $http) {
$scope.cancleInput = function () {
//not yet implemented
}
$scope.saveInput = function () {
input.title = $scope.title;
input.note = $scope.note;
$http.post("/saveData/writeData", input);
}
})
Here is my code inside C# controller:
public class saveDataController : Controller
{
public static void writeData(input input)
{
var jsonString = new JavaScriptSerializer().Serialize(input);
//other code
}
}
The http post call is not recognizing the C# method.
I am pretty sure that my URL is wrong or i am missing any C# attribute.
I am getting following error:
POST http://localhost:56171/saveData/writeData 500 (Internal Server Error)
The C# method is not hitting the break point so it is never being called by the post request.

I think you should check by getting post data from input stream data in your c# controller. you are getting 500 error because angular $http will post ajax request with "application/json" content type which is not accessible through the Request.Form collection. Try by changing public
public static void writeData(input input)
to
public static void writeData()
and use Request.InputStream to get data.
var Res = new StreamReader(Request.InputStream);

Try by creating API controller by inheriting from ApiController and decorate method with HttpPost verb as below -
public class saveDataController : ApiController
{
[HttpPost]
public static void writeData(input input)
{
var jsonString = new JavaScriptSerializer().Serialize(input);
//other code
}
}

Here is what I did to make it work:
I added custom Api configuration in WebApiConfig file.
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{Action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Then I modified the HTTP Post URL according to the new Api configuration.
$http.post("/api/saveData/writeData", input);
Then I made the C# controller inherit from ApiController.
One last change i made was that i added [HTTP POST] attribute to the C# method and removed the static keyword.
(I do not understand why having 'static' in the method definition made the method undetectable by HTTP POST.)
public class saveDataController : ApiController
{
[HttpPost]
public void writeData(input input)
{
//bunch of code
}
}

Related

.load jQuery method with data parameter for Partial Razor page

I'm working with Razor pages and can't get my dto object in javascript map to a class in the model using the jquery .load function.
So, a user clicks on a button in the UI and the following javascript runs:
$('#btnGoToResults').click(function (e) {
var dto = {
ID: 1,
CODE: 5
};
$('#divPerformanceResults').load('/PerformanceSearch?handler=ResultsPartial', dto); // Gives error 400
}
I've tried the following as well without getting it to work:
$('#divPerformanceResults').load('/PerformanceSearch?handler=ResultsPartial', JSON.stringify(dto)); // "works" since the code behind is hit but the dto values are 0
Also tried rewriting with ajax:
// Gives error 400
$.ajax({
url: '/PerformanceSearch?handler=ResultsPartial',
data: JSON.stringify(dto),
dataType: 'json',
contentType: 'application/json',
type: 'POST',
success: function (data) {
$('#divPerformanceResults').html(data);
}
});
This is the model I'm trying to map it to:
public class RequestResultModel
{
public int ID { get; set; }
public int CODE { get; set; }
}
It is the in-parameter for the method creating and returning the partial view which will contain all logic for filtering:
public PartialViewResult OnGetResultsPartial(RequestResultModel dto)
{
Results = new List<PerformanceResultModel>()
{
...
};
return new PartialViewResult
{
ViewName = "_PerformanceResults",
ViewData = new ViewDataDictionary<List<PerformanceResultModel>>(ViewData, Results)
};
}
The method works and the partial is rendered so all of that is good. It's just the dto I need to get working so I can filter the result list. I did get the following to work by switching the method parameter to an int but it's only one parameter, I'm going to need several inputs later.
$('#divPerformanceResults').load('/PerformanceSearch?handler=ResultsPartial', 'ID=15'); // This works. Only one param though
Attached the chrome log as well if that gives anything:
It feels like I'm just missing something easy here but I can't find any answers online.
Thanks!
Ok. After some more testing and research I ended up at:
https://www.learnrazorpages.com/security/request-verification
Where I found out that there are tokens added to razor pages preventing posts without it.
SO you can either ignore the token validation on global level or by class level, example:
[IgnoreAntiforgeryToken(Order = 1001)]
public class IndexModel : PageModel
{
public void OnPost()
{
}
}
Or you can do as I did in the following:
First of all, rename the method to OnPost instead of OnGet:
public PartialViewResult OnPostResultsPartial(RequestResultModel dto)
Then in the javascript call include the token like the following:
$('#btnGoToResults').click(function (e) {
var dto = {
ID: 1,
CODE: 5
};
$('#divPerformanceResults').load('/PerformanceSearch?handler=ResultsPartial',
{ dto: dto, __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() });
}
And that is it! It now maps the javascript object correctly with the class in the pagemodel :) Hope this will help others out there!
your first version of .load() was good, jquery load() method will do http post if it detects dto param as object:
$('#divPerformanceResults').load('/PerformanceSearch?handler=ResultsPartial', dto);
and then you can add [HttpPost] attribute to your Action to accept post methods
[HttpPost]
public PartialViewResult OnGetResultsPartial(WebApplication1.Models.RequestResultModel dto)
{

Razor Pages - Access razor view binded variable value after ajax get request on server

I'm trying to bind this variable on view so i don't need to send it through ajax call, not sure if that is possible but following the logic it looks like it would be.
<script>
$(function ()
{
GetStocksByUAP();
});
function GetStocksByUAP() {
#{
Model.Sector = "UAP1";
}
$.get('/dashboard/Index?handler=StocksBySector', function (response) {
swal('OK', 'Dados carregados', 'success');
console.log(response);
});
}
</script>
cs file
[BindProperty]
public string Sector { get; set; }
public IndexModel(IConfiguration config)
{
_config = config;
}
public async Task<IActionResult> OnGetStocksBySectorAsync()
{
IDbConnection con = new SqlConnection(_config.GetConnectionString("DefaultConnection"));
var result = await con.QueryAsync<DashboardViewModel>("GetStocksByUAP", new { UAP = Sector });
return new JsonResult(result);
}
To summit up, I'm trying to use the string Sector declared on the page and access it's value binded on the view after ajax get request on server. Not sure if this is possible though
If you want to process a value in a handler that gets called by an AJAX request using the GET method, you need to pass the value to the handler. You can do that as a query string value or as a route data value, but either way, it must be passed in the URL.
If you want to bind the value to a PageModel property, you must specify SupportsGet = true in the BindProperty attribute:
[BindProperty(SupportsGet=true)]
public string Sector { get; set; }
See more about how model binding works in Razor Pages here: https://www.learnrazorpages.com/razor-pages/model-binding#binding-data-from-get-requests

In Spring Boot ,During click event Html Page Redirect and Loading the values in Dropdown components using Jquery /Thymeleaf

I am using STS 3.9.0 Tool, my project is based on Spring Boot, Thymeleaf, MySQL, Html-Bootstrap and JQuery.
In Spring Boot, during a click event the Html page needs to redirect to another page and load the dynamically generated values in Dropdown components using Jquery or Thymeleaf.
Explanation
HTML click event to call #Controller to redirecting another Html page:
#RequestMapping(value = "/getflat", method = RequestMethod.GET)
public String propertyRegistration() {
return "FlatReg";
}
The URL will Be localhost:8080/getflat It will rediect to FlatReg.html, which is located in template folder.
and during load time, again hit #RestController URL to fetch the data from the DB and Load the data to Dropdown Controller
#PostMapping("/flatreg/saveflat")
public ResponseMsg doSaveFlatDetails() {
ResponseMsg responseMsg = new ResponseMsg();
try {
// My DB call Goes Here
} catch (Exception e) {
// TODO: handle exception
}
return responseMsg;
}
ResponseMsg class Like
public class ResponseMsg {
private String status;
private Object dataObj;
public ResponseMsg() {
}
public ResponseMsg(String status, Object dataObj) {
super();
this.status = status;
this.dataObj = dataObj;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getDataObj() {
return dataObj;
}
public void setDataObj(Object dataObj) {
this.dataObj = dataObj;
}
}
I don't know how to achieve this. Is there any other way? Thanks in advance.
You have two ways to achieve this.
Before rendering the page from the Controller method propertyRegistration(), add all the data you need to display in the page FlatReg page like so.
#RequestMapping(value = "/getflat", method = RequestMethod.GET)
public ModelAndView propertyRegistration() {
ModelAndView modelAndView = new ModelAndView("FlatReg");
modelAndView.addObject("data", service.getData()); //Get data from your service layer and set it in the ModelAndView to be later retreived in your FlatReg page.
return "FlatReg";
}
The second way would be to load the "FlatReg" page as you are doing right now and then using Ajax call your Controller method doSaveFlatDetails to get the required data. Check this link on how to make an ajax call.
Hope this helps.

How to set a session attribute in Javascript and then use it in a Spring Controller?

I'm trying read the value of a session attribute in Java that has been set through Javascript before. The attribute gets set correctly as Chrome shows here.
But I can't seem to get this attribute value in the Controller later.
I feel like I'm missing out on something how this whole session thing works.
Because when I debug the code, it just shows me that my MainController.java is stored in there.
My Code
main.js
function setSessionCounter(count){
listElementsCounter = count;
sessionStorage.setItem("listElementsCounter", listElementsCounter);
}
MainController.java
#RestController
#EnableWebMvc
#Scope("session")
public class MainController {
...
#RequestMapping(value = "/search", method = RequestMethod.POST)
public ModelAndView showSearchResults(#ModelAttribute("SpringWeb")SearchParameters sp, ModelMap model, HttpSession session) throws SQLException {
//Build SQL without the counter
int elementsCount = (Integer)(session.getAttribute("listElementsCounter"));
...
}
I also tried it this way in the Controller:
#RequestMapping(value = "/search", method = RequestMethod.POST)
public ModelAndView showSearchResults(#ModelAttribute("SpringWeb")SearchParameters sp, ModelMap model, HttpServletRequest request) throws SQLException {
HttpSession session = request.getSession();
//Build SQL without the counter
int elementsCount = (Integer)(session.getAttribute("listElementsCounter"));
...
}
I would really appreciate if someone could point out what I'm doing wrong (:
I think this will help you in sending ajax request to your spring controller
In Javascript
function myFunction() {
console.log("clicked on submit button");
var data = {"listElementsCounter":count}
$.ajax({
type: "POST",
url: "testurl",
data:data,
success :function(result) {
//anything you want to do after success
}
});
}
In Controller
#RequestMapping(value="/testurl" , method=RequestMethod.POST)
#ResponseBody
public void process(#RequestParam("listElementsCounter") Integer count) {
//do whatever you want to do for the count
}
JavaScript is executed on the client side, and no session attributes can be stored.
You can pass information from client to server with, for example, an Ajax call and on the server side (the controller) store the data with the session.setAttribute command.

Call c# function from javascript function [duplicate]

I want to call CsharpFunction, a C# function in code-behind, from JavaScript. I tried the code below but whether the JavaScript condition is True or False, CsharpFunction was called regardless!
JavaScript code:
if (Javascriptcondition > 0) {
<%CsharpFunction();%>
}
C# code behind:
protected void CsharpFunction()
{
// Notification.show();
}
How do I call a C# function from JavaScript?
You can use a Web Method and Ajax:
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
.CS File
namespace Csharp
{
public void CsharpFunction()
{
//Code;
}
}
JS code:
function JSFunction() {
<%#ProjectName.Csharp.CsharpFunction()%> ;
}
Note :in JS Function when call your CS page function.... first name of project then name of name space of CS page then function name
A modern approach is to use ASP.NET Web API 2 (server-side) with jQuery Ajax (client-side).
Like page methods and ASMX web methods, Web API allows you to write C# code in ASP.NET which can be called from a browser or from anywhere, really!
Here is an example Web API controller, which exposes API methods allowing clients to retrieve details about 1 or all products (in the real world, products would likely be loaded from a database):
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
[Route("api/products")]
[HttpGet]
public IEnumerable<Product> GetAllProducts()
{
return products;
}
[Route("api/product/{id}")]
[HttpGet]
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
The controller uses this example model class:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Example jQuery Ajax call to get and iterate over a list of products:
$(document).ready(function () {
// Send an AJAX request
$.getJSON("/api/products")
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
});
Not only does this allow you to easily create a modern Web API, you can if you need to get really professional and document it too, using ASP.NET Web API Help Pages and/or Swashbuckle.
Web API can be retro-fitted (added) to an existing ASP.NET Web Forms project. In that case you will need to add routing instructions into the Application_Start method in the file Global.asax:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
Documentation
Tutorial: Getting Started with ASP.NET Web API 2 (C#)
Tutorial for those with legacy sites: Using Web API with ASP.NET Web Forms
MSDN: ASP.NET Web API 2
Use Blazor
http://learn-blazor.com/architecture/interop/
Here's the C#:
namespace BlazorDemo.Client
{
public static class MyCSharpFunctions
{
public static void CsharpFunction()
{
// Notification.show();
}
}
}
Then the Javascript:
const CsharpFunction = Blazor.platform.findMethod(
"BlazorDemo.Client",
"BlazorDemo.Client",
"MyCSharpFunctions",
"CsharpFunction"
);
if (Javascriptcondition > 0) {
Blazor.platform.callMethod(CsharpFunction, null)
}
Server-side functions are on the server-side, client-side functions reside on the client.
What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load handler you can access value of variable and call the server method.
More info can be found here
and here
If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.
You can't. Javascript runs client side, C# runs server side.
In fact, your server will run all the C# code, generating Javascript. The Javascript then, is run in the browser. As said in the comments, the compiler doesn't know Javascript.
To call the functionality on your server, you'll have to use techniques such as AJAX, as said in the other answers.

Categories