I'm Using Struts2 in jsp page i have iterator values for checkbox. how to get the values in action class? Am using javascript to validate the checkboxes. So please help me to solve this problem.
i believe you have checkboxex something like
<s:form action="myaction">
<s:checkbox name="a" fieldValue="ORIGINATOR" value="%{value1}" label="A"/>
<s:checkbox name="a" fieldValue="EVALUATOR" value="%{value2}" label="B"/>
<s:checkbox name="a" fieldValue="EXECUTOR" value="%{value3}" label="C"/>
</s:form>
here is how you will get values in your action class
public class Handler extends ActionSupport{
private String[] a;
public void setA(String[] a){
this.a= a;
}
#Override
public String execute() throws Exception {
// use the checkbox values here
return Action.SUCCESS;
}
}
hope this will help you.
There are two struts tags which can generate checkbox items on the page.
checkboxlist
checkbox
The tag checkboxlist is used to populate checkboxes from a map, list or array. This will generate checkboxes to the number of items in the structure you provide. The list attribute, which is mandatory is used to specify the list or map or array. When the form gets submitted, to get the selected items in your action object, map it using attribute name. i.e. to get the selected items in action, specify the name attribute, define an array or list with the same name in action class, provide the getter and setter for the array or list. You can refer the discussion below to know more:
http://www.mkyong.com/struts2/struts-2-scheckboxlist-multiple-check-boxes-example/
The checkbox tag will generate a single checkbox item on your page. It is comparatively simple and easy to implement. Please refer the link below to understand how it works:
http://www.mkyong.com/struts2/struts-2-scheckbox-checkbox-example/
And, to validate the checkbox items, you can implement the logic as you handle the basic html + javascript. You may use cssClass attribute to specify the html class while using checkboxlist and then use jQuery select by class to get the items and validate.
Related
I have a JSP page where am printing the arraylist content via an iterator
<s:iterator var="BeanList" value="BeanList">
<option value='<s:property value="#BeanList.simpleID"/>'>
<s:property value="#BeanList.simpleText" />
</option>
</s:iterator>
Every time the user selects an option, the form submits to the action handling. I want to be able to take the value of the clicked option, and when the page is reloaded after the submit, the same value persists in the select drop down.
Any help will be greatly apprecaited,
You are using HTML Select Tag, with values populated from Struts2 Property Tag.
No JSTL is involved.
But believe me, you can avoid this using the Struts2 Select Tag directly.
Official documentation: http://struts.apache.org/release/2.3.x/docs/select.html
In Action
#Getter #Setter List<String> allCities;
#Getter #Setter String selectedCity;
In JSP:
<s:select list="allCities"
name="selectedCity" />
Faster and cleaner than iterating manually :)
Eventually you can add an optional header value:
<s:select list="allCities"
name="selectedCity"
headerKey="-1"
headerValue="Select a City" />
For that you need to declare a variable with select box name in Action class, and put setter and getter for that. And then, when you are submitting the form, the name matches and it automatically populate in Action class.
When retrieving the data set value to same variable.Then it will populate automatically by using name.
This will happen by using params interceptor internally.
I am learning Struts2 and have the following question on submitting a form with Jquery serialize. I have an action class where I have an object called Policy and the policy class has set of fields as shown below. With jquery ajax I want to set a json string in my Action class and would like to deserialize it to an object.
How much ever I try, I am not able to set the string I defined in my action class. Below is the code
Class CassPolicy{
String policyNumber;
String name;
//getsets for members
}
Action:
Class PolicyAction{
String cassPolicyString;
CassPolicy cassPolicy = new CassPolicy();
//getsets for members
String save(){
//In save method I want to convert the policyString to policy object
//policyString always returns null
}
}
JSP:
$.ajax({
url:PolicyAction.action,
type:'post',
data:$("#policyForm").serialize(),
async:true,
success:function(data){
}
});
<s:form id="policyForm">
<s:textfield name="cassPolicy.policyNumber" label="policyNumber"></s:textfield>
<s:textfield name="cassPolicy.name" label="name"></s:textfield>
</s:form>
I even tried in ajax something like data:{cassPolicyString:$("#policyForm).serialize()}
Can someone help me point to the right direction or what is the right way to achieve my task?
I figured it out finally.. The issue is form serialize does not give a json format. I used the code in below link to serialize my form as json object and added a interceptor ref element to my action in struts.xml which finally assigned my form values to cassPolicy object.
Convert form data to JavaScript object with jQuery
I am trying to find me feet with MVC4 Razor and I'm stuck with this simple problem.
When I use #Html.DisplayFor the model is always sent back as NULL, but when I use #Html.TextBoxFor this model is fully populated, what am I missing?
Thanks in advance
This is a common issue that many people miss in the asp.net mvc framework. Not just the difference in the helpers such as HiddenFor, DisplayFor, TextBoxFor - but how exactly the framework sets up automatically collecting and validating these inputs. The magic is all done with HTML5's data-* attributes. You will notice when looking at the input tag generated that there are going to be some extra properties in the form of data-val, data-val-required, and perhaps some additional data properties for types, for example numerics would be data-val-number.
These data attributes allow the jQuery extension jquery.validate.unobtrusive.js to parse the DOM and then decide which fields to validate or generate error messages.
The actual collection of posted data is reflected from the name property. This is what should map up to the model that is in the c# or vb [HttpPost] method.
Use HiddenFor when you want to provide posted data that the user does not need to be aware of.
Use DisplayFor when you want to show records but not allow them to be editted.
Use TextBoxFor when you want to allow user input or allow the user to edit a field.
EDIT
"the purpose of this view is to enable the user to view the data before submitting it to the database. Any ideas how I can achieve this?"
You could accomplish this with a duo of HiddenFor and DisplayFor. Use HiddenFor to have the values ready to be posted, and DisplayFor to show those values.
DisplayFor will not do the Model binding. TextBoxFor will do because it creates a input element in the form and the form can handle it when it is being posted. If you want to get some data in the HttpPost action and you dont want to use the TextBoxFor, you can keep that pirticulare model proeprty in a hidden variable inside the form using the HiddenFor HTML helper method like this.
#using(Html.BeginForm())
{
<p>The Type Name is</p> #Html.DisplayFor(x=>x.TypeName)
#Html.HiddenFor(x=>x.TypeName)
<input type="submit" value="Save" />
}
Use both DisplayFor and HiddenFor. DisplayFor simply displays the text and is not an input field, thus, it is not posted back. HiddenFor actually creates <input type="hidden" value="xxxx"/>
DisplayFor builds out a HTML label, not an input. Labels are not POSTed to the server, but inputs are.
I know this is a bit of an old question but you can roll your own, custom combined display control as shown below. This renders the model value followed by a hidden field for that value
#Html.DisplayExFor(model => Model.ItemCode)
Simply use what the framework already has in place
public static MvcHtmlString DisplayExFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex)
{
var sb = new StringBuilder();
sb.Append(htmlHelper.DisplayFor(ex));
sb.Append(htmlHelper.HiddenFor(ex));
return MvcHtmlString.Create(sb.ToString());
}
Do you mean during a form post? If you use DisplayFor, this creates a element which does not contain any form values. Typically you use these in conjunction with each other to create a label for your textbox, then using the Html.TextBoxFor to allow users to modify the data element.
Example:
#Html.DisplayFor(x=>x.Item)
#Html.TextBoxFor(x=>x.Item)
Will Render
Item <a text input field following>
Or in HTML
<label for="Item">Item</label><input type="Text" id="Item" name="Item"/>
In action class i am reading value from the database.
Let's say "abc".Now the "abc" value should be populated to jsp page.i.e "abc" value should set to s:hidden field in the jsp page.
Since it is single value , i don't want to use List in the action class.
Is there any other way to do that ?
Why would you want to use a list? Just provide the appropriate getter like:
public Object getAbc(){
return abc;
}
and in your page access it with simple OGNL expression like:
<s:hidden name="filedYouWantToSetThisValueTo" value="%{abc}"/>
Hope I got it right.
I have a model (entity class) Newsletter. I pass a list of Newsletter to a View and display the list of Newsletter in a table with each Newsletter across a row. Besides each Newsletter row, there is a checkbox. I will select the Newsletters that I want to send by checking the checkbox and clicking on a send button.
How can I pass the selected Newsletters to the controller?
Thanks.
In your view:
<input type="checkbox" name="newsletterIds" value="<%=newsletter.Id%>"/>
In your target controller:
public ActionResult SendNewsletters(int[] newsletterIds)
{
... do something with the ids...
}
Do something like this in your view:
<%= Html.CheckBox("cbNewColors", true) %><label for="cbNewColors">New colors</label>
in your controller, do something like this:
bool bChecked = form["cbNewColors"].Contains("true");
Simply add a boolean value called Selected to your entity class which, when passed back to the controller, will tell the controller which newsletters were selected in your list.
If you don't want to "pollute" your entity class with client metadata, you could inherit from it and add the selected bool in your derived class.
Alternatively your model can simply contain a separate list that holds references to selected newsletters or some unique identifier with which individual newsletters can later be selected from an original list.
You'll have to do some manual work, since MVC adds hidden fields for each checkbox, and relies on the model binder to deal with the value true,false coming in from the form submission (if the box was checked).
Assuming you have unique IDs available in your views, I'd recommend the following:
Manually create the checkboxes (i.e. don't use the Html helper) with the same name
< input type="checkbox" name="newsletters" value="nl_[id]" id="nl_[id]" />[name]< /label>
Accept a string[] newsletters parameter into your action that handles the post. (You may need to accept a string, and then split it on commas, I don't remember array newslettersArray = newsletters.Split(','); ;)
Convert the string into a list of newsletter IDs doing something like this:
var ids = newsletters.Select(n => int.Parse(n.Substring(2)).ToList();