I am calling a controller that redirects url. Usercontroller.cs has a ClearSessionAnCoodkies method.
I have added the route for this httpget method ClearSessionAndCookies().
Used JQuery for calling the controller method to clear the session variable and redirect tot he home page.
For some reason the call is failing and not redirecting to the home page.
Application says 404 page not found. Not sure why the call is failing :(
The following is the controller, router, and asp.net call
----------
**UserController.cs**
[HttpGet]
public IHttpActionResult ClearSessionAndCookies()
{
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
HttpContext.Current.Session.RemoveAll();
var host = Request.RequestUri.GetLeftPart(UriPartial.Authority);
return Redirect(host + "/cp");
}
**Routing**
RouteTable.Routes.MapHttpRoute(
name: "User",
routeTemplate: "api/User",
defaults: new { action = "ClearSessionAndCookies", controller = "User" }
);
**JavaScirpt**
function RedirectToWelcomePage() {
message = "Session expired. You will be redirected to home page.";
$('#sessionTimeoutTitle').text(message);
$('#sessionTimeoutModal').modal('show');
var url = 'api/User/ClearSessionAndCookies';
$.post(url, function (res) {
if (res.Success) {
sessionStorage.clear();
window.location.href = res.RedirectUrl;
}
}); }
The problem is that you are declaring the action as Get and then are calling this with a post.
[HttpGet]
public IHttpActionResult ClearSessionAndCookies()
$.post(url, function (res) {
Remove the [HttpGet] attribute and this will work.
Your route map says that if a user hits api/User it will call ClearSessionAndCookies. If you want the action in the url you may need to update your routing.
I highly recommend Route Attributes as they are cleaner to ready.
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing
Related
I use VueJS and laravel but now I can't get parameter value, please help me to solve this problem.
my VueJS code:
getTestData:function () {
let config = {
params: {
id: 1
}
};
axios.post('{{ route('get_user_data') }}', config)
.then(function (response) {
console.log(response);
// app.posts=response.data;
})
.catch(error => {
})
},
My Controller code:
public function testData(Request $request)
{
// how to get this value?
}
My route
Route::post('get-user-data','TestController#testData')->name('get_user_data');
You don't actually need a post request to get some values out of database. A get request would be more suitable.
You need to have the param in the route definition
Route::get('get-user-data/{id}','TestController#testData')->name('get_user_data');
//If you want to use post route
Route::post('get-user-data/{id}','TestController#testData')->name('get_user_data');
Then in controller method you can get the value out of the request
public function testData(Request $request)
{
$id = $request->route('id');
}
params are the URL parameters to be sent with the request
You could retrieve input from query string in your controller as:
public function testData(Request $request)
{
$id = $request->query('id');
}
I have created a dynamic web project with a Tomcat 8.5 Server and then I created an index.html that do start my first view (a simple form for login). When I click the button for login start function onPress:
onPress : function() {
var user = this.getView().byId("userInput").getValue();
var pwd = this.getView().byId("passwordInput").getValue();
var request = {
un : user,
pw : pwd
};
$.post("LoginServlet", request, function() {
alert("Ciao");
});
}
I want to pass user and pwd to this servlet (LoginServlet)
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try {
UserBean user = new UserBean();
user.setUserName(request.getParameter("un"));
user.setPassword(request.getParameter("pw"));
user = UserDAO.login(user);
/*if (user.isValid()) {
HttpSession session = request.getSession(true);
session.setAttribute("currentSessionUser", user);
response.sendRedirect("userLogged.jsp"); // logged-in page
}else
response.sendRedirect("invalidLogin.jsp"); // error page*/
} catch (Throwable theException) {
System.out.println(theException);
}
}
}
The error I am getting is:
404 Not Found. Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. Message: /LOGIN_RACMET_UI5_DynamicWebProject/LoginServlet
I need that the frontend is developed in SAPUI5, so I can't use JSP, PHP, etc.
The project is structured like this
When i do the call this is the result
I resolve it. It's wrong the url
$.post("LOGIN_RACMET_UI5_DynamicWebProject/LoginServlet", request, function() {
alert("Ciao");
});
This is right
I believe I am just missing something obvious.
I have a post that works but it gives me HTML as response. Normally that would be great if I was actually trying to load some more information on the current page. But I really want it to redirect.
The post in MainService.js
searchOpportunities : function(title, location) {
return $http
.post(
'/',
$.param({
title : title,
location : location
}),
{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
}
})
}
The response
#RequestMapping(value = "/", method = RequestMethod.POST)
public ModelAndView search_Post(#RequestParam(value = "title", required = true) String title, #RequestParam(value = "location", required = true) String location) {
ModelAndView searchView = new ModelAndView("search");
searchView.addObject("searchTitle", title);
searchView.addObject("searchLocation", location);
return searchView;
}
To clarify:
I want the page to change to the searchView after the post is sent. Right now it's just sending HTML as response... but I want redirect with the right objects "searchTitle" and "searchLocation"
Because you're just rendering the searchView view after POST, not redirecting to somewhere. If you really want to Redirect, use redirect: prefix. Suppose you have a /search endpoint and gonna redirect to it after successful POST on /, then:
#RequestMapping(value = "/", method = RequestMethod.POST)
public String search_Post(#RequestParam(value = "title", required = true) String title, #RequestParam(value = "location", required = true) String location) {
...
return "redirect:/search";
}
You could render your searchView in /search endpoint, if you want to. Read more about Redirect Views here.
I'm pretty new to the web and am trying to understand what happens on our current project. For one of our single page apps, the Controller returns a single view for the whole area.
[HttpGet]
[Url("admin")]
public virtual ActionResult Index()
{
return View(Admin);
}
In the actual Admin.cshtml, we create a backbone router that gets initialized for that section of the page and has the different views for that single page app section. My question is, I want to create an action on the route
admin/import/upload
How would that look? I don't want to actually return a View, but I want to call a function when that route gets hit to validate the uploaded file and return JSON info about the file.
You need to define a model that has a property for your uploaded file like so, it should be of type HttpPostedFileBase.
public class UploadModel
{
[Required(ErrorMessage="Please choose a file to upload.")]
public HttpPostedFileBase Photo { get; set; }
}
Then you need to make your action that accepts the specified model and returns JavaScript instead of View.
public ActionResult Upload(UploadModel model)
{
//only continue if the model is valid (i.e. all the required fields have been set)
if (ModelState.IsValid)
{
string json = "";//build your JSON here
//return the JSON as a javascript response (with the correct headers, etc)
return JavaScript(json);
}
return View(model);
}
(function() {
window.App = {
Router: {}
View: {}
};
App.Router = Backbone.Router.extend({
routes: {
'*AreaName/admin/import/upload': 'upload'
},
upload: function() {
var upload= new App.View.upload();
},
});
$(document).ready(function() {
window.routes = new App.Router;
Backbone.history.start({ pushState: true });
});
})();
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.