Struts2 Jquery Ajax form serialize - struts2

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

Related

How to pass form field values to a service method in Grails?

I'm learning Grails and I'm having a problem. I implemented scaffolding to give me the basic web forms I want and I auto-generated the controller. In the controller the create code will accept the input of a URL from a field on the form and then call a service method, let's call it executeUrl() which uses that url in some logic, which is already done.
So I have a class called myUrl that has a property urlName.
myUrl aUrl = new Url(params)
UrlService.executeUrl(aUrl)
The issue is I need to fill aUrl.urlName with something since I'm passing null above. When the user enters a url in the create form how do I grab that value and pass it to executeUrl()? Hopefully this makes sense, the tutorials have helped up to this point but I'm stuck. Any help appreciated.
So starting with your form field, assume you have something like:
<input type="text" name="url" id="url" />
In your controller you can grab the url from params like
def url = params.url
If you have a field named url in your MyUrl class you can just pass params to the constructor and groovy will bind the value for you, naming is key here
class MyUrl {
String url
}
new MyUrl( params )

Getting object type after serialization in groovy/grails

Hey guys I would appreciate it if you could help me. First of all excuse my English and secondly I would try my best to describe the problem.
As far as I know after a submitToRemote in grails the form parameters are serialized and then submitted. Now the problem:
Between two GSP pages I'm trying to send an ArrayList<foo> back and forth. To save it on each page I'm using <g:hiddenField> which is then used in the controller using params. When the the form is submitted the controller can no longer use the arrayList because it is of type string.
Also I am to do this without using cookies or sessions.
Any ideas as to how to convert to de-serialize the arrayList after the submit.
Assuming that's a simple ArrayList<Integer> you can use the method list() of params.
def myList = params.list('myList') //myList is the name in the view.
If it's a more complex list, like a list of one domain class, then you need to use commands.
Class A {
String name
}
Class ACommand {
List<A> listA = ListUtils.lazyList( [], FactoryUtils.instantiateFactory(A) )
}
View
<g:hiddenField name="listA[0].name" value="Fisrt Name" />
<g:hiddenField name="listA[1].name" value="Second Name" />
Binding the Command
class MyController {
def someAction() {
//in this example assume that this action is called in the submit of the form
ACommand command = new ACommand()
bindData(command, params) //this will populate the command with your list
}
}

MVC3 (Razor) Json Get deserialized data in the Controller

I need help again with Asp.Net MVC (Razor View Engine).
In my View (Index) I have
#model IEnumerable<Movie>
I want to pass the Model to the Controller: I stringify the model in this way:
<script type="text/javascript">
function postData(){
var urlact='#Url.Action("createDoc")';
var model ='#Html.Raw(Json.Encode(Model));
$.ajax({
data: JSON.stringify(model),
type:"POST",
url:urlact,
datatype:"json",
contentType:"application/json; charset=utf-8"
});
}
</script>
Everything seems to work, cause I know the stringified data is:
'[{"ID":1,"Title":"The Lord of the Rings: The Fellowship of the Ring","ReleaseDate":"\/Date(1007938800000)\/","Genre":"Fantasy","Price":93000000.00},{"ID":2,"Title":"The Lord of the Rings: The Two Towers","ReleaseDate":"\/Date(1039042800000)\/","Genre":"Fantasy","Price":94000000.00},{"ID":3,"Title":"The Lord of the Rings: The Return of the King","ReleaseDate":"\/Date(1070233200000)\/","Genre":"Fantasy","Price":94000000.00}]';
The problem is: in Controller, methodName "createDoc" (as declared in the script) I cannot access to the stringified data.
Following some samples founded on the web, my method is something like this:
[HttpPost]
public ActionResult createDoc(IEnumerable<Movie> movies)
{
//...using movies list
return View();
}
Why can't I access to the stringified data? How can I do it, is there some method to call to deserialize the model in the Controller method?
Also, can I use the serialize() method instead of the stringify() one? If so, what's the syntax, View & Controller side?
Thank you.
You've already got stringified data in your JavaScript variable model. You only need to call JSON.stringify on objects which aren't strings.
If you want to post the data to your action without modifying model, just pass in model without the JSON.stringify and the ModelBinder will take care of deserializing it to IEnumerable<Movie> for you.
If you want to use model as something other than a string, you'll want to call JSON.parse on the string. In other words:
var model = JSON.parse('#Html.Raw(Json.Encode(Model))');
Then, you'd want to keep your JSON.stringify call.
Finally, stringify is a method on a browser-specific object JSON, whereas serialize is a method on the ASP.NET MVC-specific Json object. Two different worlds, same name.

Struts2 checkbox with iterator

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.

How can I post an object in ASP.NET MVC?

I have a View that receives a List of an object and for each object in this list I generate a Partial View.
It's a seach result, such as Google. Each result will be wrapped in a form and each result will have its "save" post button.
So, when I post a form, I will lead user to another page where he will confirm the result he chose.
Some itens of the result I can save them to hidden fields and pass them in a FormCollection to this other page.
But, I was wondering if there's a way that I could pass this result object via post, in stead of creating hidden fields (?).
Thanks a lot!!
Hmmm, I think the answer is probably "no", but have a look at TempData and see if that might do the trick.
How about storing them in the database and assigning a resource identifier such as a GUID to the whole thing and only posting that?
You could write a custom serialize method in JS and then stuff the serialized object in a hidden field, like this:
<script type="text/javascript">
object; // from your search
var serialized = serialize(object);
$("#objectHidden").val(serialized);
</script>
Then on the ASP.NET MVC side, you would write a custom Deserialize() method and deserialize it into the object you want:
public ActionResult foo(FormCollection form)
{
MyObject object = MyObject.Deserialize(form["objectHidden"]);
}
This code is quick and dirty, but I hope it conveys the idea.

Resources