public String getVatNetAmount()
{
String expensetype = getRequest().getParameter("type");
String localAmount = getRequest().getParameter("amount");
Double localamt = Double.parseDouble(localAmount);
Double netAmount;
netAmount = getExpensesTypeManager().getVatNetAmount(expensetype,localAmount);
am = (float) ((localamt * netAmount)/100);
// getRequest().setAttribute("NetAmount", am);
return INPUT;
}
this is my java class method and i want to get data in variable am on jsp page or in javascript function?
You can use in this way :
<%
String var="sth";
%>
<script>
var value = "<%=var%>";
</script>
In Spring MVC, you can add your model to jsp using
ModelAndView mv = new ModelAndView();
mv.addObject("keyForJsp",object); // you can get data in jsp by using the key "keyForJsp"
now to get it in javascript. (using JSTL lib)
<script>
var data = '${keyForJsp}';
</script>
Related
I have JS function like this inside the #section Scripts of .cshtml view:
function SendIndexes() {
var selectedSortOption = $("#SortBy").find('option:selected');
var sortIndex = selectedSortOption.val();
var selectedFilterByTypeOption = $("#filter_marker_bytype").find('option:selected');
var filterByTypeIndex = selectedFilterByTypeOption.val();
var selectedFilterByScoreOption = $("#filter_marker_byscore").find('option:selected');
var filterByScoreIndex = selectedFilterByScoreOption.val();
var selectedFilterByStatusOption = $("#filter_marker_bystatus").find('option:selected');
var filterByStatusIndex = selectedFilterByStatusOption.val();
var markerFilterIndexes = [filterByTypeIndex, filterByScoreIndex, filterByStatusIndex];
location.href = `/Markers/MarkersList?page=#Model.PagingInfo.CurrentPage&sortIndex=${sortIndex}&markerFilterIndexes=${markerFilterIndexes}`
}
and the controller action signature like this:
public async Task<IActionResult> MarkersList(List<string> markersForUpdateIds, IEnumerable<int> markerFilterIndexes, int page = 1, string message = "", int sortIndex = 0)
{
...
}
The problem is that the array of three elements is not passed at all. However, if I only push a single variable (element) to this array, then it is passed to the controller's action as it should.
Why is this happening and how to have all three elements passed to the controller?
I'll suggest you to use [FromQuery] attribute in your parameter and format your URL like this: myparam=myvalue1&myparam=value2&myparam=myvalue3.
public async Task<IActionResult> MarkersList([FromQuery]List<string> markersForUpdateIds, [FromQuery]IEnumerable<int> markerFilterIndexes, [FromQuery]int page = 1,[FromQuery] [FromQuery]string message = "", [FromQuery]int sortIndex = 0)
{
...
}
Take a look of ModelBinding:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1#sources
For passing an array to the controller action. Data formats that use subscript numbers (... [0] ... [1] ...) must ensure that they are numbered sequentially starting at zero. Here you don't need to define an array, just format your url like this:
location.href = `/Markers/MarkersList?page=#Model.PagingInfo.CurrentPage&sortIndex=${sortIndex}&markerFilterIndexes[0]=${filterByTypeIndex}&markerFilterIndexes[1]=${filterByScoreIndex}&markerFilterIndexes[2]=${filterByStatusIndex}`
Since the data in the array is just int type data, you can omit the subscript numbers.
How can I get each attribute within a Json String?
I got the Json by converting first my array of objects in JavaScript via JSON.stringify. Afterwards I used ajax to pass the string to my servlet.
Servlet Code:
String data = request.getParameter("jsonData");
System.out.println("json data: " + data);
Result:
[{"courseID":"1","codePI":"PO-BSINSYS-02.01","curriculumID":"3"},
{"courseID":"2","codePI":"PO-BSINSYS-02.02","curriculumID":"3"}]
What I want is to get the individual values of the json so that I can assign them later to my object.
E.g.
ArrayList<Curriculum> arrCur = new ArrayList<>();
for (int x = 0; x < array.size(); x++) {
Curriculum cur = new Curriculum();
cur.setCourseID(courseID[x]);
cur.setCodePO(codePI[x]);
cur.setCurriculumID(curriculumID[x]);
arrCur.add(cur);
}
As "crowder" mentioned, you need to parse the json.
There are several ways to do it.
low-level libraries that would convert your string into a
JSONObject which is sort of a map (with keys "courseID", "codePO"
etc). At the time I used fasterxml but I see a newer approach here:
http://crunchify.com/java-how-to-parse-jsonobject-and-jsonarrays/
Higher-level libraries that would map the json directly into
Java business Objects such as "Curriculum". My own experience was
focused on replacing the simple Servlet with Spring - see for
example https://spring.io/guides/gs/rest-service/
good luck
You can use this way if you are sending arry of object from javascript and if you class -
class Curriculum{
Integer courseID;
String codePI;
Integer curriculumID;
}
Use like this -
String data = request.getParameter("jsonData");
JSONArray jsonArray = new JSONArray(data);
java.lang.reflect.Type curriculumType =new com.google.gson.reflect.TypeToken<List<Curriculum>>(){}.getType();
List<Curriculum> curriculum = new GsonBuilder().create().fromJson(jsonArray.toString(), curriculumType);
This will assign list of Curriculum. Hope this will help you.
You can also use jackson-databind API to convert your json to java object.
Create your bean for Curriculum.
class Curriculum{
Integer courseID;
String codePI;
Integer curriculumID;
public Integer getCourseID() {
return courseID;
}
public void setCourseID(Integer courseID) {
this.courseID = courseID;
}
public String getCodePI() {
return codePI;
}
public void setCodePI(String codePI) {
this.codePI = codePI;
}
public Integer getCurriculumID() {
return curriculumID;
}
public void setCurriculumID(Integer curriculumID) {
this.curriculumID = curriculumID;
}
}
Following is the code to convert your json to Curriculum object
JSONArray jsonArray = getJSONArray();
ObjectMapper objectMapper = new ObjectMapper();
for(int i =0;i<jsonArray.length();i++){
JSONObject jsonData = jsonArray.getJSONObject(i);
//convert json string to object
try {
Curriculum curr= objectMapper.readValue(jsonData.toString().getBytes(), Curriculum.class);
System.out.println(curr);
} catch (Exception e) {
e.printStackTrace();
}
}
I want to pass array (2 dimension) from controller to javascript variable. I use session to pass but this not work. In javascript code I use like this:
var data = '<%= Session["LatLon"] %>';
when run project and use inspect element, there is in data :
how to pass? Can i Pass array with 2 dim with session?
When inserting the value into Session["LatLon"], save it as JSON instead of a C# string array.
string[][] mystringarr = ...
Session["LatLon"] = JsonConvert.SerializeObject(mystringarr);
And in the view use
var data = <%= Session["LatLon"] %>;
So it will generate something like
var data = [["1.0", "1.4"], ["4.6","4.8"]];
Using JSON.NET
http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_SerializeObject.htm
What you are currently observing is a result of execution .ToString method of Session["LetLon"] object.
What you intent to receive is var data = [[1, 2], [3, 4]];.
So you can simply write a correct stringification of your two-dimensional array. I suggest to write simple extension method:
public static string ToJsString(this string[,] array) {
return Enumerable.Range(0, array.GetLength(0))
.Aggregate(new StringBuilder(),
(sbi, i) => sbi.AppendFormat(i == 0 ? "{0}" : ", {0}",
Enumerable.Range(0, array.GetLength(1))
.Aggregate(new StringBuilder(),
(sbj, j) => sbj.AppendFormat(j == 0 ? "{0}" : ", {0}", array[i,j]),
sbj => string.Format("[{0}]", sbj))),
sb => string.Format("[{0}]", sb));
}
In order to use it write then var data = <%= ((string[,])Session["LatLon"]).ToJsString() %>.
In viewmodel object, below is the property:
public IList<CollegeInformationDTO> CollegeInformationlist { get; set; }
In VIEW, javascript is as follow:
var obj = JSON.stringify('#Model.CollegeInformationlist');
alert(obj[1].State); //NOT WORKING, giving string char
$.each('#Model.CollegeInformationlist', function (i, item) {
var obj = JSON.stringify(item);
var r = $.parseJSON(obj);
alert(r.State); //just giving undefined.
});
Please guide here, how i can get JSON object in javascript.
You could use the following:
var json = #Html.Raw(Json.Encode(#Model.CollegeInformationlist));
This would output the following (without seeing your model I've only included one field):
<script>
var json = [{"State":"a state"}];
</script>
Working Fiddle
AspNetCore
AspNetCore uses Json.Serialize intead of Json.Encode
var json = #Html.Raw(Json.Serialize(#Model.CollegeInformationlist));
MVC 5/6
You can use Newtonsoft for this:
#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model,
Newtonsoft.Json.Formatting.Indented))
This gives you more control of the json formatting i.e. indenting as above, camelcasing etc.
In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().
It should be as simple as:
<script>
var json = #Json.Serialize(Model.CollegeInformationlist);
</script>
After use codevar json = #Html.Raw(Json.Encode(#Model.CollegeInformationlist));
You need use JSON.parse(JSON.stringify(json));
Pass the object from controller to view, convert it to markup without encoding, and parse it to json.
#model IEnumerable<CollegeInformationDTO>
#section Scripts{
<script>
var jsArray = JSON.parse('#Html.Raw(Json.Encode(#Model))');
</script>
}
If You want make json object from yor model do like this :
foreach (var item in Persons)
{
var jsonObj=["FirstName":"#item.FirstName"]
}
Or Use Json.Net to make json from your model :
string json = JsonConvert.SerializeObject(person);
The following code worked for me
var chartD = JSON.parse(JSON.stringify([#Json.Serialize(#Model)]));
on MyPage.aspx.cs I have List of object
protected List<MyObj> myObjList =null;
protected void Page_Load(object sender, EventArgs e)
{
myObjList = GetObjByUserId("23423");
}
on aspx page I want to assign this list of objects to JS variable
<script type="text/javascript">
$(document).ready(function () {
var BookingsList = <%=myObjList %>;
</script>
but is assign type like string=>
System.Collections.Generic.List`1[myObj]
how I can to assign my collection of object from CS to JS variable?
Try using JavaScriptSerializer like following:
c# Code
Student student = new Student();
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string StudentJson = oSerializer.Serialize(resources);
and in your aspx code get it like:
<script type="text/javascript">
var jsonStudent = <%=StudentJson%>;
</script>
Please make sure that StudentJson is a public or protected property in your backend class
You need to put the list in javascript format. In pure javascript you are looking for the following output (as an example):
var jsList = ['val1', 'val2', 'val3'];
To get this from .NET you need to use the Join function to combine list items into the appropriate format. The complete line of code looks like:
var jsList = <%= "['" + string.Join("', '", myObjList.ToArray()) + "']" %>;
Note that this assumes your "ToString" on your elements generates the output you are looking for and does not include single quotes. Hope that helps!