My view is displayed by external javascript instead of in the view itself. How do i delete multiple rows in jqgrid? I have the multiselect and multiboxonlyset equals to true. Here are my codes
View (the view is formatted in "~/Scripts/TodoList.js")
#{
ViewBag.Title = "Index";
}
<h2>TodoList</h2>
<div>
<table id="grid"></table>
<div id="pager"
</div>
<link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
Get Selected id's
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
#*<script src="~/Scripts/jquery-1.12.4.min.js" type ="text/javascript"></script>*#
<script src="~/Scripts/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="~/Scripts/TodoList.js" type="text/javascript"></script>
Todolist.js (Jqgrid)
/* File Created: February 17, 2017 */
$(function () {
$("#grid").jqGrid({
url: "/TodoList/GetTodoLists",
datatype: 'json',
mtype: 'Get',
colNames: ['Id', 'Task Name', 'Task Description', 'Target Date', 'Severity', 'Task Status'],
colModel: [
{ key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
{ key: false, name: 'TaskName', index: 'TaskName', editable: true },
{ key: false, name: 'TaskDescription', index: 'TaskDescription', editable: true },
{
key: false, name: 'TargetDate', id: "elem", index: 'TargetDate', editable: true, formatter: 'date', formatoptions: { newformat: 'd/m/Y' },
editoptions: { dataInit: function (elem) { $(elem).datepicker(); } }
},
{ key: false, name: 'Severity', index: 'Severity', editable: true, edittype: 'select', editoptions: { value: { 'L': 'Low', 'M': 'Medium', 'H': 'High'}} },
{ key: false, name: 'TaskStatus', index: 'TaskStatus', editable: true, edittype: 'select', editoptions: { value: { 'A': 'Active', 'I': 'InActive'}}}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
viewrecords: true,
// Bug Codes
// loadonce:true, //compulsory for search
//cellEdit: true, //inline edits
//cellsubmit: 'clientArray', //inline edit
caption: 'Todo List',
sortname: 'id',
sortorder: 'desc',
multiselect: true,
multiboxonly: true,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
autowidth: true,
}).navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true }, //search: true
{
// edit options
zIndex: 100,
url: '/TodoList/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// add options
zIndex: 100,
url: "/TodoList/Create",
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
//delete options
zIndex: 100,
url: "/TodoList/Delete" + ,
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using TodoListApplication.DBContext;
using TodoListApplication.Models;
namespace TodoListApplication.Controllers
{
public class TodoListController : Controller
{
//
// GET: /TodoList/
public ActionResult Index()
{
return View();
}
TodoContext db = new TodoContext();
public JsonResult GetTodoLists(string sidx, string sord, int page, int rows) //Gets the todo Lists.
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var todoListsResults = db.TodoLists.Select(
a => new
{
a.Id,
a.Severity,
a.TargetDate,
a.TaskDescription,
a.TaskName,
a.TaskStatus
});
int totalRecords = todoListsResults.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
todoListsResults = todoListsResults.OrderByDescending(s => s.TaskName);
todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
todoListsResults = todoListsResults.OrderBy(s => s.TaskName);
todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = todoListsResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
// TODO:insert a new row to the grid logic here
[HttpPost]
public string Create([Bind(Exclude = "Id")] TodoList objTodo)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.TodoLists.Add(objTodo);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successful";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
public string Edit(TodoList objTodo)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.Entry(objTodo).State = EntityState.Modified;
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
public string Delete(int Id)
{
TodoList todolist = db.TodoLists.Find(Id);
db.TodoLists.Remove(todolist);
db.SaveChanges();
return "Deleted successfully";
}
}
}
jqGrid send comma-separated list of ids in case of deleting rows in multiselect: true mode. Thus you should change string Delete(int Id) to void Delete(string id). The corresponding code could be about the following:
public void Delete(string id)
{
var ids = id.Split(',');
foreach (var id in ids) {
TodoList todolist = db.TodoLists.Find(int.Parse(id));
db.TodoLists.Remove(todolist);
}
db.SaveChanges();
}
I'd recommend you to consider too use loadonce: true option and to simplify your co return all items at once. It's the best scenario in case of displaying small number of rows (less as 1000 for example). It will simplify your server code and to improve the performance (responsibility) of the grid.
I'd recommend you additionally to verify that you use the latest version of free jqGrid (which you can download from NuGet or to load directly from CDN). You should review jqGrid options, which you use and to remove unneeded or wrong options/parameters.
I have solved my problem, with the help by #Oleg codes.
1st:
I found out that the id name that my controller uses to pass the id is "id", while my delete method in my controller says "Id" :
public string Delete(int Id) // < see this
{
TodoList todolist = db.TodoLists.Find(Id);
db.TodoLists.Remove(todolist);
db.SaveChanges();
return "Deleted successfully";
}
click here to see the debug result, pay attention to Form Data Section
So there is a name mismatched between the id specified by controller and the id that i specified in my delete method
2nd:
So i modified my delete method in controller to become:
public ActionResult Delete(string id)
{
var ids = id.Split(',');
foreach (var idsss in ids)
{
TodoList todolist = db.TodoLists.Find(int.Parse(idsss));
db.TodoLists.Remove(todolist);
}
db.SaveChanges();
var result = new { msg = "Deletion Successful ! " };
return Json(result, JsonRequestBehavior.AllowGet);
}
Now it works now, thanks to #Oleg !
Related
In my kendo grid the update button does not work after I edit through pop up editor ,"result" is a Ajax call response, since I do not use services I don't need the "read" part that's why I commented it,
DataSource Initialization:
dataSource = new kendo.data.DataSource({
transport: {
//read: {
// url: result,
// dataType: "json"
//},
update: {
url: "/AdminTool/update_grid",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "DeviceIP",
fields: {
DeviceIP: { editable: false, nullable: true },
Producer: { type: "string" },
Model: { type: "string" },
DeviceType: { type: "string" },
Description: { type: "string" },
Username: { type: "string" },
Password: { type: "string" },
PublicIP: { type: "string" },
}
}
}
});
Kendo Grid Initialization:
$("#turbingrid").kendoGrid({
dataSource: result,
scrollable: false,
columns: [
{ field: 'DeviceIP', title: 'DeviceIP', width: '100px', id: 'DeviceIP' },
{ field: 'Producer', title: 'Producer', width: '80px', editor: ProductNameDropDownEditor, },
{ field: 'Model', title: 'Model', width: '120px' },
{ field: 'DeviceType', title: 'DeviceType', width: '100px', editor:deviceTypesList },
{ field: 'Description', title: 'Description', width: '100px' },
{ field: 'Username', title: 'Username',width:'120px' },
{ field: 'Password', title: 'Password', width: '100px' },
{ field: 'PublicIP', title: 'PublicIP', width: '120px' },
{ command: ["edit"], title: " ", width: "100px" }],
editable: "popup",
edit: function() {
document.getElementsByName("DeviceIP")[0].disabled = true;
},
editable: "popup"
});
Column Editors:
function ProductNameDropDownEditor(container, options) {
$('<input name="Producer" data-type="string"\">')
.appendTo(container)
.kendoDropDownList({
valuePrimitive: true,
dataSource: mydata,
dataTextField: "Text",
dataValueField: "Text",
});
}
function deviceTypesList(container, options) {
$('<input name="DeviceType" data-type="string" \">')
.appendTo(container)
.kendoDropDownList({
dataSource: mydata_deviceType,
dataTextField: "Text",
dataValueField: "Text",
//dataValueField: "ProductName",
});
}
My Controller:
[HttpPost]
public ActionResult update_grid(TurbineDvce frm)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
The Model I want to pass
public class TurbineDvce
{
public string TurbineId { get; set; }
public string DeviceIP { get; set; }
public string Producer { get; set; }
public string Model { get; set; }
public string DeviceType { get; set; }
public string Comments { get; set; }
public string Description { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string PublicIP { get; set; }
}
Use the parameterMap function to specify what data you wish to send to the controller function when editing each individual Kendo Grid row.
You can also specify within the function different methods of returning data based on the operation type.
In your case, an example would be like:
transport: {
update: {
url:"/AdminTool/update_grid",
dataType: "json"
},
parameterMap: function (data, operation) {
if(operation !== "read" && data) {
return kendo.stringify(data);
}
}
}
your controller action method is expecting parameter name "frm". So it will be like
parameterMap: function(options, operations){
if(operation !== "read" && options{
return {frm: options}
}
}
I am trying to display a table of data returned by the following restful web api service accessible by this url. The problem is it displays only the header of the table and not the content.
/SMART/api/Build/GetAll
This url will return as output an IList of object called release, I have already tested this. The release object is structured as follows.
[Table("releases")]
public class Release
{
[Key]
public int Id { get; set; }
[StringLength(10)]
[Column("Name")]
public string Name { get; set; }
[StringLength(10)]
[Column("Type")]
public string Type { get; set; }
[Column("to_be_displayed")]
public bool ToBeDisplayed { get; set; }
}
Here is my javascript code
$.ajax({
type: 'GET',
url: '/SMART/api/Build/GetAll',
dataType: 'json',
contentType: "application/json",
success: function (data) {
alert(data);
// Get the JSON Data
var Data = new kendo.data.DataSource({
schema: {
model: {
id: "release.id",
fields: {
id: { type: "string" },
Name: { type: "string" },
Type : {type : "string"},
ToBeDisplayed: { type: "boolean" },
}
}
}
});
//Create a tab for the wip release
$('#listGrid').kendoGrid({
scrollable: false,
sortable: true,
resizable: true,
filterable: true,
autoSync: true,
dataSource: Data,
columns: [
{ field: "release.id", title: "Id" },
{ field: "release.Name", title: "Name" },
{ field: "release.ToBeDisplayed", title: "To be displayed", template: "<input name='ToBeDisplayed' type='checkbox' data-bind='checked: ToBeDisplayed' #= ToBeDisplayed ? checked='checked' : '' # class='build-tobedisplayed-checkbox'/>" },
]
});
}
});
Here is my cshtml code
<div id="listGrid" class="k-grid-content">
<div class="k-loading-mask" style="width:100%;height:100%"><span class="k-loading-text">Loading...</span><div class="k-loading-image"><div class="k-loading-color"></div></div></div>
</div>
Try the following Code:
function definitionUserGrid() {
var baseUrl = '/SMART/api/Build/GetAll';
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: baseUrl,
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: true,
pageSize: 15
});
$("#listGrid").kendoGrid({
dataSource: dataSource,
pageable: true,
reorderable: true,
resizable: true,
sortable: true,
filterable: {
mode: "row"
},
columns: [
{field: "Id",
title: "Id",
}, {
filterable: {
cell: {
enabled: true,
showOperators: false,
operator: "contains"
}
},
field: "Name",
title: "Name"
}, {
filterable: {
cell: {
enabled: true,
showOperators: false,
operator: "contains"
}
},
field: "ToBeDisplayed",
title: "To be displayed",
template: "<input name='ToBeDisplayed' type='checkbox' data-bind='checked: ToBeDisplayed' #= ToBeDisplayed ? checked='checked' : '' # class='build-tobedisplayed-checkbox'/>" },
}]
});
}
And finally:
call function definitionUserGrid()
$(function(){
definitionUserGrid();
});
this is my kendogrid code :
KendoDemosFactory.controller("MyCtrl", function ($scope, $sessionStorage) {
$scope.mainGridOptions = {
dataSource: {
transport: {
read: {url:"/User/GetUserDetail",datatype:"json"},
update: { url: "/User/UpdateUser", type: "POST" },
destroy:{ url:"/User/DeleteUser",type:"POST"},
Create:{url:"/User/CreateUser",type:"POST"}
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
},
batch: true,
pageSize: 5,
serverPaging: false,
serverSorting: false
},
sortable: true,
pageable: true,
navigatable: true,
toolbar: ["create", "save", "cancel"],
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [{
field: "FirstName",
title: "First Name",
width: "80px"
}, {
field: "LastName",
title: "Last Name",
width: "80px"
}, {
field: "Address",
width: "80px"
}, {
field: "Email",
width: "100px"
}, {
field: "Gender",
width: "80px"
},
{
field: "Salary",
width:"100px"
},
{ command: "destroy", title: " ", width: 100 }
],
editable:true
};
})
and here is my controller with my userlist and all the methods :
public ActionResult GetUserDetail()
{
IList<UserModel> userList = new List<UserModel>()
{
new UserModel{
id=1,
FirstName = "Pawan",
LastName = "Kapoor",
Address = "Mohali",
Email = "test#test.com",
Gender = "Male",
Salary = 25000
},
new UserModel
{
id=2,
FirstName = "Ayan",
LastName = "Banerjee",
Address = "Bangalore",
Email = "test1#test.com",
Gender = "Male",
Salary = 30000
},
}
}
[HttpPost]
public ActionResult CreateUser()
{
IList<UserModel> userList = new List<UserModel>();
return Json(userList, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult UpdateUser()
{
IList<UserModel> userList = new List<UserModel>();
return Json(userList, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult DeleteUser()
{
IList<UserModel> userList = new List<UserModel>();
return Json(userList, JsonRequestBehavior.AllowGet);
}
My kendo Grid is populating fine with editable functionality and all the CRUD controls but i am not able to bind data with the controller using CRUD Methods(they are not getting hit and any crud functionality is not getting persisted). Please help
Let me give you a few notes to correct your your code.
If you do not want to make batch update, send to controller only the current row.
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: options.models[0] };
}
}
Correct your update action method as follows: MVC will bind the data send from grid into UserModel.
[HttpPost]
public ActionResult UpdateUser(UserModel model)
{
// do something with model
return Json(model, JsonRequestBehavior.AllowGet);
}
This link will lead you to solve your problem
How to Display the Selected Item from Database in Kendo Grid while click the Edit Button
**My Coding Like**
var grid= $("#DivUser").kendoGrid(
{
dataSource: DataSource4,
scrollable: true,
sortable: true,
filterable: false,
reorderable: true,
resizable: true,
pageable: true,
toolbar: [ { text : "Add new record", name: "popup",
iconClass: "k-icon k-add"} ],
editable : {
mode : "inline"
columns: [
{
field: "LoginName",
title: "Login Name",
width:"175px"
},
{
field: "ScopeId",
title: "Scope Id",
editor: ScopeDropDownEditor
},
{
command: ["edit", "destroy"],
title: " ",
width: "175px"
}
]
}).data("kendoGrid");
var DataSourceScope = new kendo.data.DataSource(
{
transport:
{
read:
{
url: "WebServices/Project.asmx/GetScope",
data: "{}",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json'
},
parameterMap: function(options, operation)
{
if (operation == 'read')
return kendo.stringify(options);
}
},
schema:
{
data: function(Data)
{
return (Data.d);
},
model:
{
id: "ScopeId",
fields:
{
ScopeId: { type: "number"},
ScopeName: { type: "string"}
}
}
},
error: function(e)
{<br>
var xhr = e[0];
var statusCode = e[1];
var errorThrown = e[2];
alert('DataSourceScope - ' + xhr + ', ' + statusCode + ', ' + errorThrown);
}<br>
});
function ScopeDropDownEditor(container, options)
{
$('
data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: false,
dataSource: DataSourceScope
});
} `
in my webservice code like
public class Scopes
{
int _ScopeId;
string _ScopeName;
public int ScopeId
{
get { return _ScopeId; }
set { _ScopeId = value; }
}
public string ScopeName
{
get { return _ScopeName; }
set { _ScopeName = value; }
}
public Scopes() { }
public Scopes(int ScopeId, string ScopeName) { this.ScopeId = ScopeId; this.ScopeName = ScopeName; }
}
[WebMethod]
public List<Scopes> GetScope()
{
string StrConnectionString = ConfigurationManager.ConnectionStrings["sample"].ConnectionString;
SqlConnection SqlConnection1 = new SqlConnection(StrConnectionString);
SqlCommand SqlCommand1 = new SqlCommand("select distinct ScopeId,(select ScopeName from Scope2 where Scope2.ScopeID=User2.ScopeId)as ScopeName from User2", SqlConnection1);
DataTable DataTable1 = new DataTable();
SqlDataAdapter SqlDataAdapter1 = new SqlDataAdapter(SqlCommand1);
SqlDataAdapter1.Fill(DataTable1);
List<Scopes> ListScope = new List<Scopes>();
foreach (DataRow DataRow1 in DataTable1.Rows)
{
ListScope.Add(new Scopes(Convert.ToInt32(DataRow1["ScopeId"]), Convert.ToString(DataRow1["ScopeName"])));
}
return ListScope;
}
this is Ok..
But after Click Edit button the dropdownlist items like 1st item
for Example
ScopeName id dropdownlist
items Admin, Developer,tester
in database james is tester
if i click Edit Button Means
Name ScopeName
James admin
developer
tester
How to Bind and How i displya the SElected items?
thankx in advance.
edited
fetch data directly using java script
var xhReq = new XMLHttpRequest();
xhReq.open("POST", 'WebServices/Project.asmx/GetScope', false);
xhReq.send(null);
var DataSourceScope = JSON.parse(xhReq.responseText);
function ScopeDropDownEditor(container, options)
{
$('<input name="' + options.field + '"/>').appendTo(container).kendoDropDownList({
dataTextField: "ScopeName",
dataValueField: "ScopeId",
dataSource: DataSourceScope.d
});
}
I am using jtable http://jtable.org/ in my project. jTable is a jQuery plugin that is used to create AJAX based CRUD tables without coding HTML or Javascript.
http://i62.tinypic.com/3461eo3.jpg
jtable code for above form is
HTML code:
<div id="StudentTableContainer"></div>
JavaScript code:
<script type="text/javascript">
$(document).ready(function () {
$('#StudentTableContainer').jtable({
title: 'Student List',
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'Name ASC',
actions: {
listAction: '/Demo/StudentList',
deleteAction: '/Demo/DeleteStudent',
updateAction: '/Demo/UpdateStudent',
createAction: '/Demo/CreateStudent'
},
fields: {
StudentId: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Name',
width: '30%'
},
EmailAddress: {
title: 'Email address',
list: false
},
Password: {
title: 'User Password',
type: 'password',
list: false
},
Gender: {
title: 'Gender',
options: { 'M': 'Male', 'F': 'Female' },
list: false
},
ContinentalId: {
title: 'Continental',
options: '/Demo/GetContinentalOptions',
list: false
},
CountryId: {
title: 'Country',
dependsOn: 'ContinentalId', //Countries depends on continentals. Thus, jTable builds cascade dropdowns!
options: function (data) {
if (data.source == 'list') {
//Return url of all countries for optimization.
//This method is called for each row on the table and jTable caches options based on this url.
return '/Demo/GetCountryOptions?continentalId=0';
}
//This code runs when user opens edit/create form or changes continental combobox on an edit/create form.
//data.source == 'edit' || data.source == 'create'
return '/Demo/GetCountryOptions?continentalId=' + data.dependedValues.ContinentalId;
},
list: false
},
CityId: {
title: 'City',
width: '30%',
dependsOn: 'CountryId', //Cities depends on countries. Thus, jTable builds cascade dropdowns!
options: function (data) {
if (data.source == 'list') {
//Return url of all cities for optimization.
//This method is called for each row on the table and jTable caches options based on this url.
return '/Demo/GetCityOptions?countryId=0';
}
//This code runs when user opens edit/create form or changes country combobox on an edit/create form.
//data.source == 'edit' || data.source == 'create'
return '/Demo/GetCityOptions?countryId=' + data.dependedValues.CountryId;
}
},
BirthDate: {
title: 'Birth date',
type: 'date',
displayFormat: 'yy-mm-dd',
list: false
},
Education: {
title: 'Education',
list: false,
type: 'radiobutton',
options: [
{ Value: '1', DisplayText: 'Primary school' },
{ Value: '2', DisplayText: 'High school' },
{ Value: '3', DisplayText: 'University' }
]
},
About: {
title: 'About this person',
type: 'textarea',
list: false
},
IsActive: {
title: 'Status',
width: '15%',
type: 'checkbox',
values: { 'false': 'Passive', 'true': 'Active' },
defaultValue: 'true'
},
RecordDate: {
title: 'Record date',
width: '25%',
type: 'date',
displayFormat: 'yy-mm-dd',
create: false,
edit: false,
sorting: false //This column is not sortable!
}
}
});
//Load student list from server
$('#StudentTableContainer').jtable('load');
});
</script>
I want to have a Dropdown in my project which should take values from database through struts2 action class .
Like in the above demo code, list of continents can be accessed from database via struts2 action class (using URL pattern /Demo/GetContinentalOptions
As jtable only understands json so please guide me what should I write in Struts2 Action class and Struts.xml
Note: In your sample code you can even hardcode dropdown values
You can populate your json field with the following action. You also need a convention plugin to use annotations. To use json result you need a json plugin.
#Action(value="GetContinentalOptions", results=#Result(type="json", params = {"root", "map"}))
public class ContinentalOptionsAction extends ActionSupport {
Map<String, String> map=new HashMap<>();
public Map<String, String> getMap() {
return map;
}
#Override
public String execute() throws Exception {
map.put("1", "Asia");
map.put("2", "America");
map.put("3", "Europe");
map.put("4", "Africa");
return SUCCESS;
}
}
In the options function
var options = [];
$.ajax({ //get from server
url: '<s:url action="GetContinentalOptions"/>',
dataType: 'json',
success: function (data) {
options = data;
}
});
return options;
EDIT:
Without convention plugin you should write action configuration in struts.xml
<action name="GetContinentalOptions" class="com.action.ContinentalOptionsAction">
<result type="json">
<param name="root" value="map"/>
</result>
</action>