Web API call from a ASP.NET MVC5 application - asp.net-mvc-5

I have created a new web application with MVC template and core references having MVC and Web API.
I want to handle all the business logic through Web API controller. I have a login page view, where on form submit i want to make a call to the Web API method with the form data.
Login.cshtml
<form action="/api/Authorization/Login" method="post">
<div>
UserName: <input type="text" name="UserName" id="UserName" value="" />
</div>
<div>
Password: <input type="password" name="UserPassword" id="UserPassword" value="" />
</div>
<div>
<input type="submit" name="BtnSubmit" value="Login" />
</div>
I have added a Web API controller in the controller folder with the name 'Authorization' and on the above form submit, I'm not able to reach the method 'Login'.
Authorization Web API controller:
public class AuthorizationController : ApiController
{
public ActionResult Login(string UserName, string UserPassword)
{
// method logic
}
}
On form submit ending up with the following screen,
Please let me know what am i missing here so that i can reach the method defined under the api controller?
Also have not added any new route configs, the only config present in webApiConfig.cs is,
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

You're missing a [HttpPost] attribute above your Login() function. As it is your method will only work for GET requests.
This page will help you out: https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-1

Related

submit type button not able to submit the form in react

I'm new to react and not getting what wrong with my project structure or code and not able to trigger the submit event for the form.
Below is the function I would like to call from form mentioned below.
handleSubmit = async (event) => {
console.log('calling');
event.preventDefault();
const resp = await axios.get(`https://example.com/${this.state.userName}`);
this.props.onSubmit(resp.data);
//this.setState({ userName: '' });
};
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.userName}
onChange={event => this.setState({ userName: event.target.value })}
placeholder="GitHub username"
required
/>
<button>Add card</button>
</form>
When I start the server and try to submit the form and tried various ways of doing that as mentioned below.
<input type='submit'/>
<button onClick='submit'> Submit </button>
Click is not calling the handler function. Can anyone take a look and guide me here?
also, is there any alternative for forms in react like using div tag instead?#
You can check all code at - https://github.com/tukaram57/react.git
You just forget to add
type='submit' to the button
(Sorry if it is bad formatted but I'm on mobile)
<form onSubmit={this.handleSubmit}>
///code
<button type='submit'>Add card<button>
</form>

XSRF token mismatch

Hi I am trying to handle a form submission via a custom controller in the admin section
This is my test controller
#Controller
#RequestMapping("/" + TempController.SECTION_KEY)
public class TempController extends AdminAbstractController {
protected static final String SECTION_KEY = "test2";
#RequestMapping(value = "", method = RequestMethod.GET)
public String test(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
// This is expected by the modules/emptyContainer template, this is a custom template that gets included into the body
model.addAttribute("customView", "views/test2");
ShippingEntity shp=new ShippingEntity();
model.addAttribute("shipping",shp);
// ensure navigation gets set up correctly
setModelAttributes(model, SECTION_KEY);
// gets the scaffolding set up to display the template from the customView attribute above
return "modules/emptyContainer";
}
#RequestMapping(value = "", method = RequestMethod.POST)
public String testPost(HttpServletRequest request, HttpServletResponse response, Model model,#ModelAttribute ShippingEntity shp) throws Exception {
// This is expected by the modules/emptyContainer template, this is a custom template that gets included into the body
model.addAttribute("customView", "views/test2");
System.out.println(shp.getLink());
System.out.println(shp.getTrackingNumber());
model.addAttribute("shipping",shp);
// ensure navigation gets set up correctly
setModelAttributes(model, SECTION_KEY);
// gets the scaffolding set up to display the template from the customView attribute above
return "modules/emptyContainer";
}
}
And this is the view template :
<div class="row">
<div class="twelve columns">
<form action="#" th:action="#{/test2}" th:object="${shipping}" method="post">
<p>Id: <input type="text" th:field="*{trackingNumber}" /></p>
<p>Message: <input type="text" th:field="*{link}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</div>
</div>
The problem is that when I submit the values I get the error:
XSRF token mismatch (null). Session may be expired
I understand that this has to do with security issues however I can't find a way to make it work.
Any tips how to solve this?
Apparently it was simpler than I thought, maybe it will help someone in the future.
Just change <form> </form> to <blc:form></blc:form>

No JSON web service action associated with path /dlapp/add-file-entry and method POST liferay 6.2.4

Here is my code to upload document in liferay via jsonapi. i am adding file inside document liberary. But it show error "No JSON web service action associated with path /dlapp/add-file-entry". I am using liferay 6.2.4 ga5.
Thanks
<html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://localhost:8080/api/jsonws/dlapp/add-file-entry?repositoryId=27058&folderId=34530&sourceFileName=Screenshot&mimeType=image/png&title=hello&description=test&changeLog=not',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
});
});
</script>
<form>
<input type="file" name="file"/>
<input type="button" value="submit" id="submit"/>
</form>
</html>
Liferay JIRA
You could be encountering LPS-31943. It was a known issue related to this resource action. Please use the patching tool to upgrade to the latest patch version. I see in the comments that users are stating this problem still persists despite the bug being closed in some versions of Chrome.
Error Message
This error message is most commonly seen when you are missing required data from the request. Assuming you are fully patched, it is very likely that your data object is not correct. Even though you are sending the data as query parameters (which could be an issue depending on your JSON WS properties), the data object is still wrong and is therefore giving you the error message.
The HTTP Request
Firstly, Is there a particular reason you are calling the service this way? I believe you can achieve a better result using only HTML
<form action="http://localhost:8080/api/jsonws/dlapp/add-file-entry" method="POST" enctype="multipart/form-data">
<input type="hidden" name="repositoryId" value="27058"/>
<input type="hidden" name="folderId" value="34530"/>
<input type="hidden" name="title" value="hello"/>
<input type="hidden" name="description" value="test"/>
<input type="hidden" name="changeLog" value="not"/>
<input type="file" name="file"/>
<input type="submit" value="addFileEntry(file)">Submit</input>
</form>
This code is taken from the official Liferay knowledge base and adapted for your specific example. If you insist on using jQuery you need to stringify your data object. I would do something like this.
<html>
<head></head>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var formData = JSON.stringify($("form:first").serializeArray());
$.ajax({
url: 'http://localhost:8080/api/jsonws/dlapp/add-file-entry',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
});
});
</script>
<form>
<input type="hidden" name="repositoryId" value="27058"/>
<input type="hidden" name="folderId" value="34530"/>
<input type="hidden" name="title" value="hello"/>
<input type="hidden" name="description" value="test"/>
<input type="hidden" name="changeLog" value="not"/>
<input type="file" name="file"/>
<input type="button" value="submit" id="submit"/>
</form>
</body>
</html>
Best Practice
The sample's above are fine if you are invoking this service from an external application. If, however, you are invoking this from inside the portal (a JavaScript portlet for example) I would definitely utilize Liferay's JavaScript API and the AlloyUI tag libraries.
Liferay.Service(
'/dlapp/add-file-entry',
{
repositoryId: 12345,
folderId: 2345,
sourceFileName: 'Screenshoot',
mimeType: '',
title: '',
description: '',
changeLog: '',
cmd: {"/dlapp/add-file-entry":{}},
file: null
},
function(obj) {
console.log(obj);
}
);
Also if you are building something new you be using Liferay 7 or DXP as it is much more current.

cant make the gmaps.js search functions

i have made this simple app with gmaps.js but i need the search functions like they show it here:
http://hpneo.github.io/gmaps/examples/geocoding.html
i looked at the source code and all but it aint working.. The search button reloads the page...
my code is a follows:
<script>
$('#geocoding_form').submit(function(e){
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
}
}
});
});
</script>
<form method="post" id="geocoding_form">
<label for="address">Address:</label>
<div class="input">
<input type="text" id="address" name="address" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="map"></div>
the rest is loaded in from scripts.js you can see it in sourcecode. Why is this happening and how can i fix this?
The web app is located here, http://travelers.work/trein/
You need to change
map.setCenter(latlng.lat(), latlng.lng());
to
map.setCenter(latlng);
because the search returns a LatLng object as a result, and that's what is needed as an input for setCenter.
Here's a JS demo with your code: http://jsfiddle.net/DuRhR/3/
EDIT after comments:
Alternatively, you can pass to setCenter a LatLngLiteral
map.setCenter({lat: latlng.lat(), lng: latlng.lng()});

FacesContext redirect with POST parameters

I need to redirect page into external site with POST parameters, but I cannot use vanilla HTML <form action="url"> like it is explained here:
JSF commandButton - passing POST params to an external site
because then the form would be within a jsf form - and it doesn't work.
Is it possible to use:
FacesContext.getCurrentInstance().getExternalContext().redirect("http://example.com");
with POST parameters without additional vanilla form somehow? Or maybe there is other way to acheive this without form?
Try something like this:
JAVASCRIPT:
function redirect() {
document.getElementById("mySubmitButton").submit();
}
XHTML:
<h:form>
<span onclick="javascript:redirect()" class="linkClass">REDIRECT</span>
</h:form>
<div style="display:none:"> <!-- If you want it hidden -->
<form action="http://external/myplace.html" method="post">
<input type="hidden" value="value1"></input>
<input type="submit" id="mySubmitButton"</input>
</form>
</div>
EDIT: Added another test.
PASSING DYNAMIC PARAMETER:
In this example we assume that we are always going to send a value.
JAVASCRIPT:
function redirect(dynamicValue) {
document.getElementById("dynamicField").value = dynamicValue;
document.getElementById("mySubmitButton").submit();
}
XHTML:
<h:form>
<span onclick="javascript:redirect('myValue')" class="linkClass">REDIRECT</span>
</h:form>
<div style="display:none:"> <!-- If you want it hidden -->
<form action="http://external/myplace.html" method="post">
<input id="dynamicField" type="hidden" value=""></input>
<input type="hidden" value="value1"></input>
<input type="submit" id="mySubmitButton"</input>
</form>
</div>

Resources