How i can get value from s:checkbox - struts2

i want to get value from table using s:checkbox
i create this app using struts2
My code is as follows:
testAction.java
public class test extends ActionSupport{
private String id;
private List<String> colors;
private String yourColor;
public String getYourColor() {
return yourColor;
}
public void setYourColor(String yourColor) {
this.yourColor = yourColor;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<String> getColors() {
return colors;
}
public void setColors(List<String> colors) {
this.colors = colors;
}
private List<ColorBean> list ;
public List<ColorBean> getList() {
return list;
}
public String execute() {
return SUCCESS;
}
public String display() {
return NONE;
}
}
struts.xml
<action name="testAction" class="action.testAction" method="display">
<result name="none" type="tiles">index</result>
</action>
<action name="resultAction" class="action.testAction">
<result name="success">result.jsp</result>
</action>
index.jsp
<s:form action="resultAction" namespace="/">
<table id="dataTables-example">
<thead>
<tr>
<th>sheck</th>
<th>IF</th>
<th>CINOURC</th>
<th>NOMOURC</th>
</tr>
</thead>
<tbody>
<s:iterator value="list">
<tr>
<td>
<s:checkbox name="yourColor"
fieldValue="%{list}" theme="simple" />
</td>
<td><s:property value="id" /></td>
<td><s:property value="cin" /></td>
<td><s:property value="name" /></td>
</tr>
</s:iterator>
</tbody>
</table>
result.jsp
<h2>
value : <s:property value="yourColor"/>
</h2>
the problem is when i receive the value in result page i receive an object like
[bean.RarBean#42a3fe79, bean.RarBean#2d2cfd76, bean.RarBean#54e8f278]
and when i try to do something like this
<h2>
value : <s:property value="yourColor.id"/>
</h2>
i receive nothing ..
how i can handle this problem

Related

MVC ModelState.IsValid not working

I am using below code to validate my model, but when I click on the 'Save Employee' button on the CreateEmployee view, the page is returning to CreateEmployee view without a validation messages.
Model
public class Employee
{
[Key]
public int EmployeeId { get; set; }
[Required(ErrorMessage="Enter First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage="Enter Last Name")]
[StringLength(6,ErrorMessage="Last Name should not contain more than 6 characters")]
public string LastName { get; set; }
public int Salary { get; set; }
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
#*<meta name="viewport" content="width=device-width" />*#
<title>CreateEmployee</title>
<script type="text/javascript">
function ResetForm() {
document.getElementById("txtFirstName").value = "";
document.getElementById("txtLastName").value = "";
document.getElementById("txtSalary").value = "";
}
</script>
</head>
<body>
<div>
<form action="SaveEmployee" method="post">
#Html.ValidationSummary()
<table>
<tr>
<td>First Name:</td>
<td>
<input type="text" id="txtFirstName" name="FirstName" value="" /></td>
</tr>
<tr>
<td colspan="2" align="right">#Html.ValidationMessage("FirstName")</td>
</tr>
<tr>
<td>Last Name:</td>
<td>
<input type="text" id="txtLastName" name="LastName" value="" /></td>
</tr>
<tr>
<td colspan="2" align="right">#Html.ValidationMessage("LastName")
</td>
</tr>
<tr>
<td>
<input type="submit" value="SaveEmployee" />
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
Controller
public ActionResult SaveEmployee(Employee e,string BtnSubmit)
{
switch (BtnSubmit)
{
case "Save Employee":
if (ModelState.IsValid)
{
EmployeeBuisnessLayer objEBL = new EmployeeBuisnessLayer();
objEBL.SaveEmployee(e);
return RedirectToAction("Index");
}
else
{
return RedirectToAction("CreateEmployee");
}
case "Cancel":
return RedirectToAction("Index");
}
return new EmptyResult();
}
Don't redirect. You will lose modelstate. You need to let the method run to completion and pass the model back to the view.
Controller
[HttpPost]
public ActionResult CreateEmployee(Employee e, string BtnSubmit) {
switch (BtnSubmit) {
case "SaveEmployee":
if (ModelState.IsValid) {
EmployeeBuisnessLayer objEBL = new EmployeeBuisnessLayer();
objEBL.SaveEmployee(e);
return RedirectToAction("Index");
}
case "Cancel":
return RedirectToAction("Index");
default:
return new EmptyResult();
}
return View(e);
}
Your Form also needs to post to the CreateEmployee
View
<form action="CreateEmployee" method="post">

How to get client side generated class list to MVC post action argument?

I have one form where I am generating some control dynamically (Which is list some class . in image add product artwork section) When I click on submit button how can i get this values in post Action method's argument so that I can use this value in collection.
For reference I have attached the image where i have option for multiple Artwork oprion
[HttpPost]
public ActionResult Add(Graphic graphicToAdd,Enumerable<GraphicArtwork> artworkOption)
{
// I want value in artworkOption
}
public class GraphicArtwork
{
[Key]
public int GraphicArtworkId { get; set; }
public int GraphisId { get; set; }
[Required(ErrorMessage = "The {0} is required.")]
[DisplayName("Option Text")]
[StringLength(500)]
public string ArtOptionText { get; set; }
public decimal Price { get; set; }
[DisplayName("Active")]
public bool IsActive { get; set; }
public DateTime CreatedDate { get; set; }
[NotMapped]
public int TotalRecordCount { get; set; }
}
This is my view :
<div class="editor-field PrintOptions">
<table data-bind="visible :customArtworks().length > 0">
<thead>
<tr>
<td class="editor-label">Option</td>
<td class="editor-label">Price</td>
<td></td>
</tr>
</thead>
<tbody data-bind="foreach: customArtworks">
<tr>
<td>
<input placeholder="Enter Artwork Text" type="text" data-bind="value: ArtOptionText'}" />
</td>
<td>
<input placeholder="Enter Price" type="text" data-bind="value: Price" />
</td>
<td>
<img title="Add" src="~/Content/images/icon_add.png">
<img title="Delete" style="margin-left:10px;" src="~/Content/images/icon_delete.png">
</td>
</tr>
</tbody>
</table>
</div>
For more detail : I am generating my dynamical control using knockout.js
// Ko Implemntation
function GraphicArtwork(ArtOptionText, Price) {
var self = this;
self.ArtOptionText = ArtOptionText;
self.Price = Price;
self.formattedPrice = ko.computed(function () {
var price = self.Price;
return price ? "$" + price.toFixed(2) : "0.00";
})
}
function GraphicArtworkViewModel() {
var self = this;
self.customArtworks = ko.observableArray([GraphicArtwork(null, null)]);
self.add = function () {
self.customArtworks.push(new GraphicArtwork(null, null));
};
self.remove = function (GraphicArtwork) {
self.customArtworks.remove(GraphicArtwork);
};
}
ko.applyBindings(new GraphicArtworkViewModel());
Add This binding :
<td>
<input placeholder="Enter Artwork Text" type="text" data-bind="value: ArtOptionText,attr:{name: '['+$index()+'].ArtOptionText'}" />
</td>
<td>
<input placeholder="Enter Price" type="text" data-bind="value: Price,attr:{name: '['+$index()+'].Price'}" />
</td>
AND in Code Behind
public ActionResult Add(Graphic graphicToAdd,IEnumerable<GraphicArtwork> listOfGraphicArtwork)
{
// listOfGraphicArtwork will hold all the required data
}

ognl.MethodFailedException: Method failed for object [java.lang.NoSuchMethodException:([Ljava.lang.String;)]

I have a userCreateDate Field, When I Add the data for the first time, it gets inserted into resp. table,but when I try to update the same record by onClick of Javascript and setting the value to the respective textfields, it gives Invalid field value for field "userTypeEntity.userCreatedDate". and the date field value is coming null in validate() method.
Can you help me get out of this error.
My JSP is:
<table width="100%" style="border-collapse: collapse;" border="0" bordercolor="#006699" align="center">
<tr>
<s:hidden id="id" name="userGroupEntity.userGroupId"/>
<s:textfield id="name" name="userGroupEntity.userGroupName" key="label.groupName" maxlength="15" size="30" required="true" labelSeparator=""/>
<s:textfield id="desc" name="userGroupEntity.userGroupDesc" key="label.groupDesc" maxlength="20" size="30" required="true" labelSeparator=""/>
<s:textfield id="cdate" name="userGroupEntity.userCreatedDate" key="label.CreatedDt" size="30" readonly="true" cssStyle="background-color:#E7EBDD;" labelSeparator=""/>
<s:textfield id="mdate" name="userGroupEntity.userModifiedDate" key="label.ModifiedDt" size="30" readonly="true" cssStyle="background-color:#E7EBDD;" labelSeparator=""/>
<s:radio id="status" name="userGroupEntity.userActive" key="label.status" list="userGroupStatus" required="true" labelSeparator=""/>
</tr>
<tr>
<td colspan="100%" align="center"><hr></td>
</tr>
<tr>
<td colspan="100%" align="center">
<s:submit id="save" theme="simple" name="save" key="label.save"/>
<s:reset id="reset" theme="simple" name="reset" key="label.reset"/>
<s:a href="userGroupView">
<img border="0" src='<s:url value="/images/b_cancel.gif"></s:url>' width="50" height="20" alt="Go to User Group Master">
</s:a>
</td>
</tr>
<tr>
<td colspan="100%">
<s:if test="hasActionMessages()"><div style="color:red;"><s:actionmessage/></div></s:if>
</td>
</tr>
</table>
<s:if test="{groupList.size() != 0}">
<s:iterator value="groupList" var="group">
<tr>
<td><s:property value="userGroupName"/></td>
<td><s:property value="userGroupDesc"/></td>
<td><s:property value="userCreatedDate"/></td>
<td><s:property value="userModifiedDate"/></td>
<td align="center"><b>Edit</b>
| <b>Delete</b>
</td>
</tr>
</s:iterator>
</s:if>
And My Action Class is:
public class UserGroupAction extends ActionSupport implements Preparable{
private static Log log = LogFactory.getLog(UserGroupAction.class);
/**
*
*/
private static final long serialVersionUID = 1L;
private String result;
private UserGroupEntity userGroupEntity;
private Map<String, String> userGroupStatus;
private List<UserGroupEntity> groupList;
private int userSaveStatus;
private int groupId;
public String userGroupSave() throws Exception{
log.info("...In UserGroupAction.userGroupSave...");
// int userSaveStatus = 1;
try {
int groupId = userGroupEntity.getUserGroupId();
System.out.println("Group Id: "+groupId);
System.out.println("Group Name: "+userGroupEntity.getUserGroupName());
if(groupId == 0){
userSaveStatus = UserGroupController.userGroupSave(userGroupEntity);
System.out.println("userSaveStatus: "+userSaveStatus);
if(userSaveStatus == 1 ){
addActionMessage("Group Added Successfully.");
result = SUCCESS;
}else{
addActionMessage("Group Already Exists.");
result = SUCCESS;
}
}else{
userSaveStatus = UserGroupController.userGroupSave(userGroupEntity,groupId);
System.out.println("userSaveStatus: "+userSaveStatus);
if(userSaveStatus == 1 ){
addActionMessage("Group Updated Successfully.");
result = SUCCESS;
}else{
addActionMessage("Group Already Exists.");
result = SUCCESS;
}
}
} catch (Exception e) {
System.out.println("...In Catch of UserGroupAction.execute ...");
result = ERROR;
e.printStackTrace();
}
return result;
}
#Override
public void validate(){
System.out.println("...In UserGroupAction.validate ...");
if(isEmpty(userGroupEntity.getUserGroupName())){
addFieldError("userGroupEntity.userGroupName", "Group name can't be empty.");
}
if(isEmpty(userGroupEntity.getUserGroupDesc())){
addFieldError("userGroupEntity.userGroupDesc", "Group description can't be empty.");
}
if(isEmpty(userGroupEntity.getUserActive())){
addFieldError("userGroupEntity.userActive", "Please select status.");
}
//System.out.println("Create Date:: "+userGroupEntity.getUserCreatedDate());
}
}
Here all other testField values are coming in action, but date field values are coming null... Please Help. Am Stucked here...
My Javascript is:
function userGroupEdit(flag,id,name,desc,cdate,mdate){
alert(flag+id+name+desc+cdate+mdate);
if(flag=='edit'){
document.getElementById("id").style.display="block";
document.getElementById("id").value=parseInt(id);
document.getElementById("name").value=name;
document.getElementById("desc").value=desc;
document.getElementById("cdate").value=cdate;
document.getElementById("mdate").value=mdate;
document.getElementById("statusY").checked=true;
}else{
//document.getElementById("save").style.display="block";
}
//window.location = url;//"${pageContext.request.contextPath}/"+url;
return true;
}
I got the solution: In Javascript I formatted the date as
function setDateFormat(strDate){
//strDate '2014-06-18'
//alert(strDate.length);
if(strDate!=''){
var y,m,d;
y = strDate.substring(0,4);//alert(y);
m = strDate.substring(5,7);//alert(m);
d = strDate.substring(8,10);//alert(d);
var newDate = m+"/"+d+"/"+y;
//alert(newDate);
return newDate;
}else{
if(typeof(strDate) == 'string'){
newDate = '';
return newDate;
}
}
}
These date fields are now getting persisted in DB and there is no Struts2 field message like Invalid field value for field from validate method.

auto refresh of div in mvc3 ASP.Net not working

ViewData.cshtml(Partial View)
This is partial View
<table id="users" class="ui-widget ui-widget-content" width="100%" align="center">
<thead>
<tr class="ui-widget-header ">
<th width="30%" align="center">Date</th>
<th width="30%" align="center">Bill Amount</th>
<th width="30%" align="center">PayNow</th>
</tr>
</thead>
<tbody>
#{
for (int i = #Model.bill.Count - 1; i >= 0; i--)
{
<tr>
<td width="30%" align="center">#Model.billdate[i]</td>
<td width="30%" align="center">#Model.bill[i]</td>
<td width="30%" align="center">
<a class="isDone" href="#" data-tododb-itemid="#Model.bill[i]">Paynow</a>
</td>
</tr>
}
}
</tbody>
</table>
Index.cshtml(View)
This is my view
<script type="text/javascript">
$(document).ready(function () {
window.setInterval(function () {
var url = '#Url.Action("ShowScreen", "Home")';
$('#dynamictabs').load(url)
}, 9000);
$.ajaxSetup({ cache: false });
});
</script>
<div class="dynamictabs">
#Html.Partial("ShowScreen")
</div>
HomeController.cs(Controller)
This is home controller
public ActionResult Index()
{
fieldProcessor fp= new fieldProcessor();
return View(fp);
}
public ActionResult ShowScreen()
{
return View();
}
fieldProcessor.cs
My Model
public class fieldProcessor
{
public List<int> bill { get; set; }
public List<string> billdate { get; set; }
}
Still Div is not getting refreshed.
This line:
$('#dynamictabs').load(url)
Should be:
$('.dynamictabs').load(url)
...because your div has a class of dynamictabs, not an id.
It will work with some code changes:
1) like greg84 said:
This line:
$('#dynamictabs').load(url)
Should be:
$('.dynamictabs').load(url)
2) Your controller should be like this:
public ActionResult ShowScreen()
{
fieldProcessor fp = new fieldProcessor();
/*Load fieldProcessor object*/
return View(fp);
}
public ActionResult Index()
{
fieldProcessor fp = new fieldProcessor();
/*Load fieldProcessor object*/
return View(fp);
}
3) ShowScreen and Index should be strong typed views:
#model YourApp.Models.fieldProcessor
4) When your code call the partial view, you should pass the model, like this:
<div class="dynamictabs">
#Html.Partial("ShowScreen",Model)
</div>

how to get id of selected item value from selectOneMenu in jsf?

I have dropdown of categories. On selecting particular category, I have rendered another dropdown of subcategories of that category. I want id of selected subcategory.But I am not getting it.My code is:
<tr>
<td align="right">
<h:outputText value="Select Main Category:"></h:outputText>
</td>
<td>
<h:selectOneMenu id="cmbcategory" value="#{categoryBean.categoryID}" required="true" requiredMessage="Select Category" >
<f:selectItem itemLabel="--Select Category--" itemValue="0"></f:selectItem>
<f:selectItems value="#{categoryBean.categories}" var="item" itemLabel="#{item.categoryName}" itemValue="#{item.categoryID}"></f:selectItems>
<f:ajax event="valueChange" render="cmbsubcategory" immediate="true" listener="#{categoryBean.SubcategoriesByCategory()}"/>
</h:selectOneMenu>
</td>
<td><h:message for="cmbcategory"></h:message></td>
</tr>
<tr>
<td align="right">
<h:outputText value="Select Sucategory:"></h:outputText>
</td>
<td>
<h:selectOneMenu id="cmbsubcategory" value="#{categoryBean.subCategoryID}" required="true" requiredMessage="Select Subcategory">
<f:selectItem itemLabel="--Select Subcategory--" itemValue="0"></f:selectItem>
<f:selectItems value="#{categoryBean.SubcategoriesByCategory()}" var="item" itemLabel="#{item.subcategoryID}" itemValue="#{item.subcategoryID}"></f:selectItems>
</h:selectOneMenu>
</td>
<td><h:message for="cmbsubcategory"></h:message></td>
</tr>
And my bean is:
public int getCategoryID() {
return CategoryID;
}
public void setCategoryID(int CategoryID) {
this.CategoryID = CategoryID;
}
public String getCategoryName() {
return CategoryName;
}
public void setCategoryName(String CategoryName) {
this.CategoryName = CategoryName;
}
public Collection<Category> getCategories() {
categories=abr.getAllCategory();
return categories;
}
public Collection<Subcategory> SubcategoriesByCategory()
{
System.out.print("catid...... "+CategoryID);
subcats= abr.searchAllSubcategoriesByCategory(CategoryID);
return subcats;
// +"size....."+ subcats.size());
}
public String getSubCatName() {
return SubCatName;
}
public void setSubCatName(String SubCatName) {
this.SubCatName = SubCatName;
}
public int getSubCategoryID() {
System.out.print("subcatid...... "+SubCategoryID);
return SubCategoryID;
}
public void setSubCategoryID(int SubCategoryID) {
this.SubCategoryID = SubCategoryID;
}
public Collection<Subcategory> getSubcats() {
return subcats;
}
public void setSubcats(Collection<Subcategory> subcats) {
this.subcats = subcats;
}
public void setCategories(Collection<Category> categories) {
this.categories = categories;
}
You are mixing up a property getter with an action method. A getter should return the property and an action method should be void or return a String.
Change
public Collection<Subcategory> SubcategoriesByCategory() {
..
}
to
public void searchSubcats() {
subcats= abr.searchAllSubcategoriesByCategory(CategoryID);
}
and call this method in your ajax request:
<f:ajax .. listener="#{categoryBean.searchSubcats}"/>
The selectItems in the second drow-down then need to reference the getter for subcats:
<f:selectItems value="#{categoryBean.subcats}" ... />

Resources