Action routing goes to same controller - html

I'm trying to link to a different controller with a HTTPPost action, however, when I try to it just appends my route values onto the current page's controller. For example, if I'm trying to link from Site/ViewIndex to Page/createPage with a form and a HTTPPOST, then it throws a 404 and says it can't access Site/Page/createPage. Why is it doing this and how can I stop it?
Here is my site/createPage:
public ActionResult createPage(int siteId, string title, string description, bool isBlog = false)
{
if (string.IsNullOrWhiteSpace(title) ||
string.IsNullOrWhiteSpace(description))
{
return RedirectToAction("ViewIndex", new { siteId = siteId, message = "Please fill out all fields" });
}
try
{
Ops.PageOps.createPage(title, description, siteId, isBlog);
return RedirectToAction("ViewIndex", "Site", new { siteId = siteId, message = "Page created!" });
}
catch (Exception e)
{
return RedirectToAction("ViewIndex", new { siteId = siteId, message = "Error occured: " + e.Message });
}
}
Here is my form:
<form method="post" action="Page/createPage">
<input class="form-field form-control" type="text" name="title" placeholder="Page Title" />
<input class="form-field form-control" type="text" name="description" placeholder="Page Description" />
<input class="form-field form-control" type="hidden" name="siteId" value="#site.Id" />
Blog page? <input class="form-field" type="checkbox" value="true" name="isBlog" /><br /><br />
<input class="btn btn-info" type="submit" value="Create" />
</form>
And I doubt it's any relevance but here's my Site controller:
public class SiteController : Controller
{
/// <summary>
/// The create page
/// </summary>
/// <returns></returns>
public ActionResult CreateIndex()
{
return View();
}
[HttpPost]
public ActionResult Create(string title, string description, bool privateSite = false)
{
Ops.SiteOps.createSite(Authenticated.AuthenticatedAs, title, description, privateSite);
return RedirectToAction("Index", "Home");
}
public ActionResult ViewIndex(int siteId, string message = null)
{
ViewBag.message = message;
ViewBag.siteId = siteId;
return View();
}
}

Use the Html.BeginForm helper method to render your form tag. This will render the correct relative path to your HttpPost action in your form's action attribute.
#using(Html.BeginForm("CreatePage","Page"))
{
<input class="form-field form-control" type="text" name="title" placeholder="Title" />
<input class="form-field form-control" type="text" name="description" " />
<input class="form-field form-control" type="hidden" name="siteId" value="#site.Id" />
Blog page? <input class="form-field" type="checkbox" value="true" name="isBlog" />
<input class="btn btn-info" type="submit" value="Create" />
}

Related

How to send a post request to the Spring controller using ajax

I want to send a post request to the spring controller using ajax. But it doesn't work. I would be grateful if anyone could tell me, what I have done worngly.
$("#myprofile").on('submit',function(e){
console.log("in changes ave"+ $("#firstname").val());
console.log("in changes ave"+ $("#lastname").val());
console.log("in changes ave"+ $("#current_password").val());
console.log("in changes ave"+ $("#new_password").val());
var myJSON = JSON.stringify({
"firstname" : $("#firstname").val(),
"lastname" : $("#lastname").val(),
"current_password" : $("#current_password").val() ,
"new_password" : $("#new_password").val()
});
$.ajax({
type : "POST",
url : "/edit_profile",
dataType:"json",
contentType: "application/json",
data : myJSON,
success : function(mydataa) {
console.log("Successful")
},
error: function(dataa){
alert(dataa.responseText)
}
});
})
Here is my controller:
#ResponseBody
#RequestMapping(value = "/edit_profile", method = RequestMethod.POST, consumes = "application/json")
public ModelAndView editProfile(#RequestParam("firstname") String firstname,
#RequestParam("lastname") String lastname, #RequestParam("new_password") String new_password,
#RequestParam("current_password") String current_password) {
ModelAndView modelAndView = new ModelAndView();
//some logic here
user = profileRepository.changeUserInformation(user, firstname, lastname, new_password, current_password);
}
modelAndView.setViewName("profile");
return modelAndView;
}
And here is my html page:
<form class="col" id="myprofile">
<input type="text" class="form-control border-0" name="firstname" id="firstname" th:value="${currentUser.firstname}">
<input type="text" class="form-control border-0" name="lastname" id="lastname"
th:value="${currentUser.lastname}">
<input type="password" class="form-control border-0" placeholder="current password" name="current_password" id="current_password">
<input type="password" class="form-control border-0" placeholder="new password" name="new_password" id="new_password">
<input type="password" class="form-control border-0" name="confirm_password"
id="confirm_password" placeholder="confirm new password">
<button id = "changesave-btn" type="submit" class="save button-2">SAVE CHANGES</button>
</form>
I get Error 400 Bad request as the message returned from the alert line and I see this output in my console:
Required String parameter 'firstname' is not present
Thanks in advance,
Since you send a JSON payload, there is no request parameter.
Create a POJO to store the Ajax POST data.
public class MyProfile {
private String firstname;
private String lastname;
private String new_password;
private String current_password;
public MyProfile() {
}
// getter/setter ..
}
Accept the Ajax POST data with #RequestBody
#ResponseBody
#RequestMapping(value = "/edit_profile", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ModelAndView editProfile(#RequestBody MyProfile myProfile) {
// ...
}

View page return null pointer exception

when im trying to access the signUp, as i see in the debug, there is a problem when the code get to the view.
im getting run time exception "System.Web.Mvc.WebViewPage.Model.get returned null."
Please HELP
here is the full failure :
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Web.Mvc.WebViewPage.Model.get returned null.
happen here :
#{
ViewBag.Title = "SignUp";
}
SignUp.cshtml
<body>
<div class="signup-form">
<form class="signup-form" action="SignupSubmit">
<div class="col-md-8 order-md-1">
<h2>SignUp</h2>
<h3>Create an account</h3>
<h4 class="mb-3">Please complete your details : </h4>
<div class="row">
<div class="col-md-4 mb-3">
<label for="firstName">Id number</label>
<input type="text" class="form-control" name="userid" id="idnum" value="#Model.userid"> #Html.ValidationMessageFor(u => u.userid)
<div class="invalid-feedback">
Valid id number is required.
</div>
</div>
<div class="col-md-4 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" value="#Model.firstName"> #Html.ValidationMessageFor(u => u.firstName)
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-md-4 mb-3">
<label for="lastName">Last name</label>
<input type="text" class="form-control" name="lastName" id="lastName" value="#Model.lastName"> #Html.ValidationMessageFor(u => u.lastName)
<div class="invalid-feedback">
Valid last name is required.
</div>
</div>
</div>
<div class="mb-3">
<label for="email" class="col-sm-2 col-form-label">Email </label>
<input type="email" class="form-control" name="email" id="inputEmail" placeholder="you#example.com" value="#Model.email"> #Html.ValidationMessageFor(u => u.email)
<div class="invalid-feedback">
Please enter a valid email address for shipping updates.
</div>
</div>
<div class="mb-3">
<label for="inputPassword" class="col-sm-2 col-form-label">Password</label>
<input type="password" class="form-control" name="password" id="inputPassword" placeholder="Password" value="#Model.password"> #Html.ValidationMessageFor(u => u.password)
<div class="invalid-feedback">
Please enter a valid password with numbers and letters.
</div>
</div>
<label class="checkbox-inline"><input type="checkbox" required="required"> I accept the Terms of Use & Privacy Policy</label>
<hr class="mb-4">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
#Html.ActionLink("Already have an account? Login here. ", "SignIn", "User", new { area = "" }, new { #class = "navbar-brand" })
</div>
</form>
</div>
UserController.cs
public ActionResult SignUp()
{
return View(new User());
}
public ActionResult SignupSubmit(User user)
{
if (ModelState.IsValid)
{
AddUserToDB(user);
}
else
{
return View("SignUp");
}
TempData["Falied"] = "You can now connect with your details";
return RedirectToAction("SignIn", "User");
}
[HttpPost]
public bool AddUserToDB(User u)
{
try
{
UserDal dal = new UserDal();
dal.users.Add(u);
dal.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var errors in ex.EntityValidationErrors)
{
foreach (var validationError in errors.ValidationErrors)
{
// get an error message
string errorMessage = validationError.ErrorMessage;
Trace.TraceInformation("Property: {0} Error: {1}",
validationError.PropertyName,
validationError.ErrorMessage);
}
}
return false;
}
return true;
}
User.cs
public class User
{
[Key]
[Required]
[RegularExpression("^[0-9]{9}$", ErrorMessage = "ID must be with 9 numbers")]
public string userid { get; set; }
[Required]
[RegularExpression("^[a-z]+$", ErrorMessage = "First Name must be only Characters")]
public string firstName { get; set; }
[Required]
[RegularExpression("^[a-z]+$", ErrorMessage = "Last Name must be only Characters")]
public string lastName { get; set; }
[Required]
[RegularExpression(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "Email must conatain characters seperate with #")]
[StringLength(100, MinimumLength = 4, ErrorMessage = "Email must be with at least 4 characters or Maximum 50 caracters")]
public string email { get; set; }
[Required]
[RegularExpression(#"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$", ErrorMessage = "Password must conatain eight characters, at least one letter and one number")]
[StringLength(8, MinimumLength = 8, ErrorMessage = "Password must be with 8 Characters")]
public string password { get; set; }
public string permission { get; set; }
public float totalHoures { get; set; }
}
the issue was that user was not sending here ...
else {
return View("SignUp");
}
so i changed the code to
return View("SignUp",user);
and now it working as expected.
my view is strongly typed view, and i just want to see the errors messages next the text box which are not passed the validation successfully.

Values not being insert into Database from JSP form

I'm trying to get the doPost() method in my servlet to insert values from a JSP form into the database, however it doesn't seem to be working and I'd like to know if anyone here could help me out. Thank you. Here's the code below:
public boolean addOrder(Connection conn) {
boolean success = false;
// Declare JDBC objects
PreparedStatement ps = null;
try {
String sql = "INSERT INTO OrderInfo(SizeOfPizza, NumOfToppings, Quantity, "
+ " Delivery, Price) VALUES(?, ?, ?, ?, ?);";
ps = conn.prepareStatement(sql);
ps.setString(1, order.getPizzaSize());
ps.setInt(2, order.getNumToppings());
ps.setInt(3, order.getQuantity());
ps.setBoolean(4, order.isDelivery());
ps.setDouble(5, order.getPrice());
int count = ps.executeUpdate();
if (count > 0) {
success = true;
}
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
} finally {
DBConnection.closeJDBCObjects(conn, ps);
return success;
}
}
Servlet to insert into the database
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
OrderDAO dao = new OrderDAO();
DBConnection conn = (DBConnection)this.getServletContext().getAttribute("dbConn");
boolean ordersuccess = dao.addOrder(conn.getConnection());
HttpSession session = request.getSession();
session.setAttribute("ordersuccess", ordersuccess);
request.getRequestDispatcher("ReceiptPage.jsp").forward(request, response);
}
Page to fill in form and send off to the servlet
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Pizza Order Page</title>
<%
String fname = request.getParameter("firstName");
String lname = request.getParameter("lastName");
%>
<style>
body{
background-color: silver;
}
#title{
background-color: gray;
}
</style>
</head>
<body>
<h1 id="title" align="center">Hello <%out.print(fname + " " + lname);%></h1>
<p>Please fill out your order information</p>
<p><b>Delivery Options</b></p>
<form action="ReceiptServlet.do" method="POST">
<Select name="deliveryOption">
<option value="Pick Up">Pick Up</option>
<option value="Delivery">Delivery</option>
</Select>
<br>
<p><b>Size Options</b></p>
<input type="radio" name="size" value="Small">Regular ($5.00)<br><br>
<input type="radio" name="size" value="Large">Large ($7.00)
<br>
<p><b>Topping Choices</b></p>
<input type="radio" value="Pepperoni" name="topping">Pepperoni ($1.00)</option><br>
<input type="radio" value="Mushroom" name="topping">Mushroom ($1.00)</option><br>
<input type="radio" value="Olives" name="topping">Olives ($1.00)</option><br>
<input type="radio" value="Sausage" name="topping">Sausage ($1.00)</option><br>
<input type="radio" value="Pineapple" name="topping">Pineapple ($1.00)</option><br>
<br>
<p><b>Enter the amount of pizzas you would like to order</b></p>
<input type="text" name="pizzaQty">
<br><br>
<input type="submit" value="Place Order">
</form>
</body>

2 submit buttons on same form with MVC 3. Only one submit button is working in IE 9

I gave submit buttons a name, and then inspected the submitted value in the controller method. When I click on register button it is not triggering action method, which is on server. This is working fine with chrome and IE 10 and above it is not working in IE9.
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="PostValue" value="UploadImage" />
<input type="submit" name="PostValue" value="Register" />
<% Html.EndForm(); %>
I have not experienced on that.
But there is a solution to this problem if you don't want to use submit buttons with the same name:
#using (Html.BeginForm("PostNews", "Home", FormMethod.Post))
{
<input type="submit" name="submit.Publish" value="Publish News" />
<input type="submit" name="submit.Save" value="Save News" />
}
public class HomeController : Controller
{
[HttpPost, ActionName("PostNews"), ActionRequired("submit.Publish")]
public ActionResult PublishNews()
{
ViewBag.Message = "Your app description page.";
return View(...);
}
[HttpPost, ActionName("PostNews"), ActionRequired("submit.Save")]
public ActionResult SaveNews()
{
return View(...);
}
}
public class ActionRequiredAttribute : ActionMethodSelectorAttribute
{
private readonly string _submitButtonName;
public ActionRequiredAttribute(string submitButtonName)
{
_submitButtonName = submitButtonName;
}
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var actionRequired = controllerContext.RequestContext.HttpContext.Request.Form[_submitButtonName];
return !string.IsNullOrEmpty(actionRequired);
}
}

JSON simple program showing error

Tyring a simple example of json but it is showing error.
I have included gson-2.2.3.jar in class path.
I am using netbeans 7.1. This program is not deploying.
Apache tomcat log is showing:
Unable to load configuration. - action - file:/D:/APP/webApp1/build/web/WEB-INF/classes/struts.xml:10:73
Caused by: Error building results for action sayHi in namespace - action - file:/D:/APP/webApp1/build/web/WEB-INF/classes/struts.xml:10:73
Caused by: There is no result type defined for type 'json' mapped with name 'success'. Did you mean 'json'? - result - file:/D:/APP/webApp1/build/web/WEB-INF/classes/struts.xml:11:33
I am trying simple example. Please see what is the proble.
Action Class
public class AjaxActions extends ActionSupport {
private String name;
private String greeting;
public String sayHi() {
greeting = "HI " + name;
return ActionSupport.SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
Struts.xml
<package extends="struts-default,json-default" name="ajax-package" namespace="/ajax">
<action class="example.AjaxActions" method="sayHi" name="sayHi">
<result type="json">
</result>
</action>
</package>
in jsp file
<form action="" id="introForm">
<label for="name">Enter Your Name</label>
<input name="name">
<input type="submit">
</form>
<script>
$(function(){
$("#introForm").submit(function(){
var formInput=$(this).serialize();
$.getJSON('ajax/sayHi.action', formInput,function(data) {
$('.result').html('' + data.greeting + '');
return false;
});
});
</script>
add struts2-json-plugin.jar according to struts2 version in your project libraries.
if you are using struts2.3.4 then use struts2-json-plugin2.3.4.jar
And change your in your struts.xml
<package extends="struts-default,json-default"
to
<package extends="json-default".
And use the following html code.
<form action="" id="introForm">
<label for="name">Enter Your Name</label>
<input type="text" id="name" name="name">
<input onclick="javascript:getResultData();" type="submit">
<span id="resultHtml"></span>
</form>
<script>
function getResultData(){
var formInput=$("#name").val();
vat inputData={"name":formInput}
$.getJSON('ajax/sayHi.action', inputData,function(data) {
$("#resultHtml").html('' + data.greeting + '');
return false;
});
}
</script>