I have an array list in action class. I want to access this arraylist in my jsp page along with a checkbox. if the checkbox is checked i want to get the associated value of checkbox in another actionclass. how can i do this??
Action class:
public class CreateModuleAction extends ActionSupport{
private List modNameList=new ArrayList();
private int size;
public String manageModule()
{
ManageModule ob=new ManageModule();
modNameList=ob.selectModule();
if(modNameList.isEmpty()) {
addActionError("Module list is empty!!!");
return ERROR;
}
else{
setSize(modNameList.size());
return SUCCESS;
}
}
public List getModNameList() {
return modNameList;
}
public void setModNameList(List modNameList) {
this.modNameList = modNameList;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
jsp page:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../css/style.css" rel="stylesheet" type="text/css" />
<title>Admin Module Management</title>
</head>
<body>
<div class="main">
<div class="header">
<!-- Page heading-->
<jsp:include page="/templates/heading.jsp" flush="true"/>
</div>
<div class="menu">
<!-- Page menu-->
<jsp:include page="/templates/menu.jsp" flush="true"/>
</div>
<div class="content">
<!-- page content-->
<div id="right_top" style="position:absolute; left:900px; top:300px;;">
<img src="../images/add.jpg"/>Add
<img src="../images/edit.jpg"/>Edit
<img src="../images/add.jpg"/>Delete
</div>
<s:iterator status="size" value="modNameList">
<s:checkbox name="modNameCheck" fieldValue="true" value="modNameList"/>
<s:property value="modNameList"/>
</s:iterator>
<s:actionerror/>
</div>
<div class="footer" style="margin-left: 50%">
<!-- page footer-->
<jsp:include page="/templates/footer.jsp" flush="true"/>
</div>
</div>
</body>
</html>
Why dont you use struts2 checkboxlist tag
<s:form action="myAction">
<s:checkboxlist list="modNameList" name="modNameCheck"/>
</s:form>
Now in yoyr myAction action class declare
private List modNameCheck; //with getter/setter
It will have entries which were checked in the jsp
If you want submit values from checkboxes to action then you need form in your JSP. If you want to display checked/unchecked checkboxes depending on some values from action then you need some condition check in value attribute.
<s:checkbox name="modNameCheck" value="list.contains(something)"/>
Related
I want to be able to use a Stimulus Controller in multiple places in a web app. I want do something like this:
<div data-controller="mycontroller">
<OneComponent />
</div>
<SomeOtherComponent />
<div data-controller="mycontroller">
<NewComponent />
</div>
But the controller just seem to connect to the first Component and not in the second. Is it possible to use it as I'm intending to?
Thanks!
Stimulus controllers can be reused. See this sample.
Possible problems that may prevent this from working is if there is a JS error, or that you expect elements in nested components to be used in the parent component, if they have not been rendered yet.
const application = Stimulus.Application.start()
application.register("hello", class extends Stimulus.Controller {
connect() {
console.log("connect to", this.element.getAttribute("data-language"))
}
static get targets() {
return [ "name" ]
}
greet() {
if (this.element.getAttribute("data-language") == "es-ES") {
console.log(`¡Hola, ${this.nameTarget.value}!`);
} else {
console.log(`Hello, ${this.nameTarget.value}!`);
}
}
})
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/stimulus/dist/stimulus.umd.js"></script>
</head>
<body>
<div data-controller="hello" data-language="en-US">
<input data-hello-target="name" type="text" value="John">
<button data-action="click->hello#greet">Greet</button>
</div>
<div data-controller="hello" data-language="es-ES">
<input data-hello-target="name" type="text" value="Jose">
<button data-action="click->hello#greet">Saudar</button>
</div>
</body>
</html>
This is View File here Displaying error for student in list
#model IEnumerable<Controller2View.Models.Students>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div class="container">
<div class="btn btn-default">
<ul class="list-group">
#foreach (var std in ViewData["StudentData"] as List<Students>)
{
<li class="list-unstyled">
std.StudentName
</li>
}
</ul>
</div>
</div>
</body>
</html>
This is Controller file which have a list defined and viewdata for transferring data from controler to View. Model also defined well but dont know whu its not working.
public ActionResult Index()
{
List<Students> studentList = new List<Students>() {
new Students(){ StudentId=1, StudentName="Steve"},
new Students(){ StudentId=2, StudentName="Bill"},
new Students(){ StudentId=3, StudentName="Ram"}
};
ViewData["StudentData"] = studentList;
return View(studentList);
}
Would be good to know what exactly is not working. But still 2 things:
Either use the view with a model or with ViewData.
I guess you get a list of 3 items with "std.StudentName", that's because it must read #std.StudentName
Use below code in controller
public ActionResult Index()
{
var studentList = new List<Students>() {
new Students(){ StudentId=1, StudentName="Steve"},
new Students(){ StudentId=2, StudentName="Bill"},
new Students(){ StudentId=3, StudentName="Ram"}
};
return View(studentList);
}
Now, In View use below code
#model IEnumerable<Controller2View.Models.Students>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div class="container">
<div class="btn btn-default">
<ul class="list-group">
#foreach (var std in Model)
{
<li class="list-unstyled">
std.StudentName
</li>
}
</ul>
</div>
</div>
</body>
</html>
Hopefully it will works as I am using model directly instead of casting it into list.
I tried lot,googling even took help from laracast.com/discuss but could not solve the issue. why the session flash is not working? please drop your suggestion. Here is my code of all_controll.php
<?php
namespace App\Http\Controllers;
use DB;
use App\Quotation;
use App\Model\students;
use Illuminate\Http\Request;
//use Auth;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Session;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
class all_control extends Controller
{
public function index()
{
return view('index');
}
public function insert_students(Request $request)
{
$std = new students();
$std->name = $request->input('name');
$std->email = $request->input('email');
$std->save();
return redirect('/index');
}
public function getform()
{
return view('form');
}
public function postform()
{
$roll = Input::get('roll');
$ct_number = Input::get('ct');
DB::table('test')->insert(array(
'name' => $roll,
'age' => $ct_number
));
Flash :: Session ("key",
"You have done successfully!!!!");
//Session::flash('message','You have done successfully!!!!');
return Redirect::route('getform');
//return redirect('/index');
}
}
and my form.blade.php code is given below
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<meta charset="UTF-8">
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<h1>Form</h1>
<h3>
<?php
if(Session::has('key')){
echo Session::get('key');
}
?>
</h3>
<form action="{{ URL::route('postform') }}" method="post" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<legend>Form Title</legend>
<div class="form-group">
<label for="">name</label>
<input type="text" class="form-control" name="roll" id="roll" placeholder="Input...">
</div>
<div class="form-group">
<label for="">Marks of Physisc CT</label>
<input type="number" class="form-control" name="ct" id="ct" placeholder="Input...">
</div>
<button type="submit" class="btn btn-primary">Hit the Button</button>
</form>
</div>
</body>
</html>
You can use the built in redirect() helper which will flash the data to the session by using ->with().
public function postform(Request $request)
{
$roll = $request->roll;
$ct_number = $request->ct;
DB::table('test')->insert([
'name' => $roll,
'age' => $ct_number
]);
return redirect('index')->with('key', 'You have done successfully');
}
SIDENOTE:
Inject Request into your method and use it instead of Input. Input was used in laravel 4 while injecting the Request class is the recommended way in laravel 5.1
I have also faced same issue with you.
My solution is to include use Flash; on top of the controller that you wanted to use the Laracasts Flash plugin.
Hope this helps.
return redirect()->route('posts.index')->with('success_msg', 'Post deleted successfully');
Here Success_msg is used to display msg on redirected page.
I'm new to MVC so I'm not completely sure that I have the model tied into the controller and view as it should be. I'm trying to have a message pop up after an error has occured. In this case the error occurs after the submit button has been clicked.
The view...
#if (ViewBag.Message != null)
{
<script>
$(document).ready(function () {
alert('#ViewBag.Message');
});
</script>
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Guru Dental: Request Demo</title>
<!-- CSS -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,400">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Droid+Sans">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lobster">
<link rel="stylesheet" href="~/Content/assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="~/Content/assets/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="~/Content/assets/css/animate.css">
<link rel="stylesheet" href="~/Content/assets/css/magnific-popup.css">
<link rel="stylesheet" href="~/Content/assets/flexslider/flexslider.css">
<link rel="stylesheet" href="~/Content/assets/css/form-elements.css">
<link rel="stylesheet" href="~/Content/assets/css/style.css">
<link rel="stylesheet" href="~/Content/assets/css/media-queries.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Favicon and touch icons -->
<link rel="shortcut icon" href="~/images/favicon.ico" type="image/x-icon">
<link rel="icon" href="~/images/favicon.ico" type="image/x-icon">
</head>
<body>
<!-- Top menu -->
<nav class="navbar" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#top-navbar-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<br>
<img class="logo-size" src="~/images/guru-dental-slogan.png" alt="">
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="top-navbar-1">
<ul class="nav navbar-nav navbar-right">
<li><a href='#Url.Action("Index", "Home")'><br><br>Home</a></li>
<li>
<a href='#Url.Action("Contact", "Home")'><br><br>Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Title -->
<div class="page-title-container">
<div class="container">
<div class="row">
<div class="col-sm-12 wow fadeIn">
<h1>Demo Request</h1>
</div>
</div>
</div>
</div>
<!-- Contact Us -->
<div class="contact-us-container">
<div class="container">
<div class="row">
<div class="col-sm-7 contact-form wow fadeInLeft">
#using (Html.BeginForm("DemoSubmit", "CRM", FormMethod.Post))
{
<h2>Rep Details</h2>
<div class="form-group">
<label for="contact-firstname">HSD Rep Code</label>
<input type="text" name="hsdrepcode" placeholder="Enter your HSD Rep code..." class="contact-name" id="contact-name">
</div>
<div class="form-group">
<label for="contact-lastname">Rep First Name</label>
<input type="text" name="hsfirstname" placeholder="Enter your Rep first name..." class="contact-name" id="contact-name">
</div>
<div class="form-group">
<label for="contact-lastname">Rep Last Name</label>
<input type="text" name="hslastname" placeholder="Enter your Rep last name..." class="contact-name" id="contact-name">
</div>
<h2>Doctor Details</h2>
<div class="form-group">
<label for="contact-currentlocation">Doctor's First Name</label>
<input type="text" name="firstname" placeholder="Enter your doctor's first name.." class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label for="contact-currentlocation">Doctor's Last Name</label>
<input type="text" name="lastname" placeholder="Enter your doctor's last name..." class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label for="contact-currentlocation">Doctor's Phone Number</label>
<input type="text" name="phonenumber" placeholder="Enter your doctor's phone number..." class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label for="contact-currentlocation">Doctor's E-mail</label>
<input type="text" name="emailaddress" placeholder="Enter your doctor's e-mail..." class="contact-subject" id="contact-subject">
</div>
<button type="submit" class="btn">Submit</button>
}
</div>
The controller...
public ActionResult RequestDemo()
{
return View();
}
[HttpPost]
public ActionResult DemoSubmit(LeadInfo leadInfo)
{
string salesEmail = CRMModels.GetNextSalesEmail();
ViewBag.Message = CRMModels.AddLeadToCRM(leadInfo);
if (ViewBag.Message == null)
{
EmailModels.SendEmailForLead(leadInfo, salesEmail);
return RedirectToAction("Index", "Home");
}
else
return RequestDemo();
}
}
The model...
if (hsdRepId != Guid.Empty)
{
lead.Attributes["ree_hsdrepresentative"] = new EntityReference("ree_henryscheinrepresentative", hsdRepId);
service.Create(lead);
}
else
{
message = "Invalid HSD Representative Code";
}
return message;
In the DemoSubmit function, if there is a message to display, I need to go back to the view to display it. How do I do that? I tried to do with a redirect but that just gives me a new page with none of the data that was entered in and it didn't display the message.
Thanks,
Gary
On controller once you got error you can add error message to modalState
ModelState.AddModelError("", "Invalid HSD Representative Code");
and to pop the error alert you can use html extension method to pop the message
public static HtmlString PopAlert(this HtmlHelper htmlHelper, string alertType = "danger",
string heading = "")
{
if (htmlHelper.ViewData.ModelState.IsValid)
return new HtmlString(string.Empty);
var sb = new StringBuilder();
sb.AppendFormat("<div class=\"alert alert-{0} alert-block\">", alertType);
sb.Append("<button class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>");
if (!heading.IsNullOrWhiteSpace())
{
sb.AppendFormat("<h4 class=\"alert-heading\">{0}</h4>", heading);
}
sb.Append(htmlHelper.ValidationSummary());
sb.Append("</div>");
return new HtmlString(sb.ToString());
}
On view you simply call the Html extension method like this
#Html.PopAlert()
hope this will help you :)
You have a number of problems with your code, in particular the fact you not binding any controls to you model so returning the view will always display empty controls. You should also include validation attributes on you properties to prevent posting and saving potentially bad data. Your view is also generating invalid html (lots of duplicate id attributes) and <label> tags which are not really labels (clicking on them wont set focus to the associated control because you don't associate them with a control.
Based on your view, your LeadInfo class looks something like (suggested attributes added)
public class LeadInfo
{
[Display(Name = "HSD Rep code")]
[Required(ErrorMessage = "Please enter your HSD Rep code")]
public string hsdrepcode { get; set; }
[Display(Name = "Rep first name")]
[Required(ErrorMessage = "Please enter your Rep first name")]
public string hsfirstname { get; set; }
.....
[Display(Name = "Doctor's e-mail")]
[Required(ErrorMessage = "Please enter your doctor's e-mail")]
[EmailAddress]
public string emailaddress{ get; set; }
}
You GET method should then be
public ActionResult RequestDemo()
{
LeadInfo model = new LeadInfo();
return View(model);
}
and the view should then strongly typed html helpers to bind to your properties and to display validation errors
#model LeadInfo
....
#using(Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true) // this is where you custom error message will be displayed
#Html.LabelFor(m => m.hsdrepcode) // displays the text associated with the DisplayAttribute and is associated with the following textbox
#Html.TextBoxFor(m => m.hsdrepcode, new { placeholder="Enter your HSD Rep code...", #class="contact-name"})
#Html.ValidationMessageFor(m => m.hsdrepcode)
....
<button type="submit" class="btn">Submit</button>
}
You should also include the following scripts (preferably using #Scripts.Render() and the bundling and minification features of MVC)
jquery-{version}.js
jquery.validate.js
jquery.validate.unobtrusive.js
You should also be using layouts (master pages)
The post method is then
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RequestDemo(LeadInfo model) // not sure why you would change the name of the method?
{
if(!ModelState.IsValid)
{
return View(model); // return the view to fix any validation errors
}
string errorMessage = CRMModels.AddLeadToCRM(leadInfo);
if (errorMessage == null)
{
string salesEmail = CRMModels.GetNextSalesEmail();
EmailModels.SendEmailForLead(leadInfo, salesEmail);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", errorMessage);
return View(model);
}
}
Its not clear what the error message you want to return is, but you code suggests it might be associated with the hsdrepcode property, in which case, modify the code to associate the error with a particular property
ModelState.AddModelError("hsdrepcode", errorMessage);
Side note: Most of your code is ignoring the benefits of using MVC, to the point you may as well not use it. I recommend you go the the MVC site and work through the tutorials,
I want to fetch a text box value from jsp to my action class.
But my action class in not getting called while submitting the page.
My code are
Jsp page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="AddedColor" method="post">
<div class="box">
<span class="label">Color Name</span>
<span class="ib"> <input type="text" name="color" id="color"/></span>
</div>
<div class="box">
<input type="button" id="submit_color" value="Add Color"/>
</div>
</form>
</body>
</html>
In struts.xml
<package name="colorpkg" extends="struts-default">
<action name="AddedColor" class="iland.work.ColorAction" method="insert">
<result name="success">/pages/colors/showColors.jsp</result>
</action>
</package>
In ActionClass
public class ColorAction extends ActionSupport {
private String color;
//getter and setter of color
public String insert() {
System.out.println("-> ColorAction insert()");
System.out.println(getColor());
return SUCCESS;
}
}
try this:
<div class="box">
<input type="submit" id="submit_color" value="Add Color"/>
</div>