Get dropdown value and text in controller mvc4 razor - asp.net-mvc-4

I am working on MVC4 project. I have form where dropdownlist is populated with text and value field.
#Html.DropDownList("SourceDropDownList", new SelectList(""), "-Select-", new { #class = "validate[required]" })
This dropdown is populated from other dropdown change event
here is that code
function OnSourceFacilityDropDownChange(source, e) {
$("#SourceDropDownList").empty();
var curOpt = new Option('-Select-', "");
$("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
if (source.value != '') {
var url = getUrl() + '/AdminPanel/GetIns/?id=' + Math.random();
$.ajax({
url: url,
data: { clientid: $("#SourceDropDown").val(), strFacility: source.value }, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
$.each(data, function (index, item) {
var curOpt = new Option(item.T, item.T);
curOpt.setAttribute("title", item.T);
$("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
});
},
error: function (request, status, error) { alert("Status: " + status + "\n Exception Handling : \n" + request.responseText); },
complete: function () {
$("#divLoading").hide();
}
});
}
else {
}
}
and code in AdminPanel/GetIns controller is
public JsonResult GetInspection(int clientid, string strFacility)
{
var objlist = (from d in Context.tbl_insp
orderby d.str_insp ascending
where d.clientid.Equals(ClientId))
select new { T= d.str_inspname, V= d.dte_start.Value.ToShortDateString()}).ToArray();
Array InspectionList = objlist;
return Json(InspectionList, JsonRequestBehavior.AllowGet);
}
And in model class i have initialized the property of dropdown
public string SourceDropDownList{ get; set; }
now i am getting only text values of what i select in SourceDropDownList dropdown..
How do i get the value also ??

Try with this,Just Example
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
#Html.DropDownList("CustomerNameId", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Script
<script type="text/javascript">
$(document).ready(function () {
$("#CustomerId").change(function () {
var Id = $("#CustomerId").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { CustomerNameId: Id },
success: function (listItems) {
var STSelectBox = jQuery('#CustomerNameId');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
Controller
public JsonResult GetCustomerNameWithId(string CustomerNameId)
{
int _CustomerNameId = 0;
int.TryParse(CustomerNameId, out _CustomerNameId);
var listItems = GetCustomerNameId(_CustomerNameId).Select(s => new SelectListItem { Value = s.CID.ToString(), Text = s.CustomerName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}
Model
public class CustomerModel
{
public int CustomerId { get; set; }
public int CustomerNameId { get; set; }
}

Related

Send back FullCalendar events to .NET with AJAX

I would like to sendback FullCalendar events to .NET with an AJAX request. I create a custom button for that :
#{
ViewData["Title"] = "Planning visites";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>#ViewData["Title"]</h1>
<div id='calendar'></div>
#section scripts
{
<script>
let date = new Date();
let month = String(date.getMonth() + 1).padStart(2, '0');
let day = String(date.getDate()).padStart(2, '0');
let year = date.getFullYear();
let dateDuJour = year + '-' + month + '-' + day;
let dateDuJourplusunan = (year + 1) + '-' + month + '-' + day;
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
//themeSystem: 'bootstrap5',
//plugins: [ timeGridPlugin ],
initialView: 'timeGridWeek',
selectable: true,
selectOverlap: false,
//selectMirror: true,
validRange: {
start: dateDuJour,
end: dateDuJourplusunan
},
customButtons: {
enregistrermodifs: {
text: 'enregistrer',
click: function() {
var eventsobj = calendar.getEvents();
var data = JSON.stringify(eventsobj);
//var data = JSON.serialize(eventsobj);
alert(data);
$.ajax({
type: 'POST',
url: '#Url.Action("MAJAgenda","Agenda")',
//contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // when we use .serialize() this generates the data in query string format. this needs the default contentType (default content type is: contentType: 'application/x-www-form-urlencoded; charset=UTF-8') so it is optional, you can remove it
contentType: 'application/json; charset=utf-8',
data: data,
success: function(result) {
alert('Successfully received Data ');
console.log(result);
},
error: function() {
alert('Erreur : enregistrement non effectué');
console.log('Failed');
}
});
}
}
},
headerToolbar: {
left: 'prev,next,today,enregistrermodifs',
center: 'title',
right: 'dayGridMonth,timeGridWeek,dayGridDay'
},
buttonText: {
today: 'Aujourdhui',
month: 'mois',
week: 'semaine',
timeGridWeek: 'jour',
day: 'jour',
list: 'liste'
},
initialDate: dateDuJour,
navLinks: true, // can click day/week names to navigate views
editable: true,
dayMaxEvents: true, // allow "more" link when too many events
events:'#Url.Action("RecupDonneesAgenda","Agenda")?annonceId=#ViewBag.AnnonceId',
select: function(info) {
calendar.addEvent({
//id: info.startStr,
title: 'Indisponibilité',
start: info.startStr,
end: info.endStr,
allDay: false
});
},
eventClick: function(info) {
var eventobj = info.event;
eventobj.remove();
}
});
calendar.render();
calendar.setOption('locale', 'fr');
});
</script>
}
Here's my model in .NET :
public class AgendaAJAX
{
public string? title { get; set; }
public DateTime? start { get; set; }
public DateTime? end { get; set; }
}
And here's my action method :
[HttpPost]
public async Task<IActionResult> MAJAgenda(AgendaAJAX? agenda)
{
string userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
////List<Agenda> agenda = await _context.Agendas.Where(a => a.AnnonceID == annonceId && a.Personne1 == userID).ToListAsync();
//JsonResult result = new JsonResult(agenda);
return View("Agenda");
}
THE AJAX call works well : here's the JSON data :
[{"title":"Indisponibilité","start":"2022-06-09T07:30:00+02:00","end":"2022-06-09T12:30:00+02:00"},{"title":"Indisponibilité","start":"2022-06-10T10:00:00+02:00","end":"2022-06-10T15:00:00+02:00"},{"title":"Indisponibilité","start":"2022-06-11T07:00:00+02:00","end":"2022-06-11T09:30:00+02:00"}]
The problem is that I don't receive any data in the action method : agenda remains null.
I don't understand why.
If you can help me please.
Thanks.

ASP.NET CORE MVC With Google Charts - No Data

Trying to implement Google Chart with ASP.Net CORE MVC.
Been at it for two days, but I can not figure out my mistake. I don't get an error, and I can see the array in the console, but no data.
VIEWMODEL
public class ZipCodes
{
public string ZipCode { get; set; }
public int ZipCount { get; set; }
}
CONTROLLER
public ActionResult IncidentsByZipCode()
{
var incidentsByZipCode = (from o in _context.Incident
group o by o.ZipCode into g
orderby g.Count() descending
select new
{
ZipCode = g.Key,
ZipCount = g.Count()
}).ToList();
return Json(incidentsByZipCode);
}
VIEW
function IncidentsByZipCode() {
$.ajax({
type: 'GET',
url: '#Url.Action("IncidentsByZipCode", "Controller")',
success: function (response) {
console.log(response);
var data = new google.visualization.DataTable();
data.addColumn('string', 'ZipCode');
data.addColumn('number', 'ZipCount');
for (var i = 0; i < response.result.length; i++) {
data.addRow([response.result[i].ZipCode, response.result[i].ZipCount]);
}
var chart = new google.visualization.ColumnChart(document.getElementById('incidentsByZipCode'));
chart.draw(data,
{
title: "",
position: "top",
fontsize: "14px",
chartArea: { width: '100%' },
});
},
error: function () {
alert("Error loading data!");
}
});
}
Because the api you use is not Column Chart, the data cannot be added and rendered correctly. According to the official example, you need to make some changes.
Here is the ajax code.
<script>
//Generate random colors
function bg() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ',' + g + ',' + b + ")";
}
function IncidentsByZipCode() {
$.ajax({
type: 'GET',
url: '#Url.Action("IncidentsByZipCode","home")',
success: function (response) {
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
var obj = [
["Element", "Density", { role: "style" }],
];
$.each(response, function (index, value) {
obj.push([value.zipCode, value.zipCount, bg()])
})
var data = google.visualization.arrayToDataTable(obj);//This is method of Column Chart
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2]);
var chart = new google.visualization.ColumnChart(document.getElementById('incidentsByZipCode'));
chart.draw(data,
{
title: "",
position: "top",
fontsize: "14px",
chartArea: { width: '100%' },
});
}
},
error: function () {
alert("Error loading data!");
}
});
}
IncidentsByZipCode()
This is the controller.
public ActionResult IncidentsByZipCode()
{
//var incidentsByZipCode = (from o in _context.Incident
// group o by o.ZipCode into g
// orderby g.Count() descending
// select new
// {
// ZipCode = g.Key,
// ZipCount = g.Count()
// }).ToList();
var incidentsByZipCode = new List<ZipCodes>
{
new ZipCodes{ ZipCode="code1", ZipCount=3},
new ZipCodes{ZipCode="code2",ZipCount=4},
new ZipCodes{ZipCode="code3",ZipCount=2},
new ZipCodes{ZipCode="code4",ZipCount=9},
};
return Json(incidentsByZipCode);
}
Result, and you can also refer to this document
.

Update Cascading Dropdown in Mvc5

Hi i want to know how to update or edit cascading dropdown like (Country,state,City)in mvc5.I have created 3 cascading dropdowns Country State city.If i select Country State will append in state dropdownn like wise city. Now i save these 3 dropdown values in table successfully. But now i stuck with edit option. I donno how to bind the saved value to these dropdowns in edit from.
My model
public class UCustomerManagementViewModel
{
public string UCountry { get; set; }
public string UState { get; set; }
public string UCity { get; set; }
}
My Controller code
public JsonResult GetCountries()
{
var Countries = db.Countries.ToList();
return Json(Countries, JsonRequestBehavior.AllowGet);
}
public JsonResult GetStatesByCountryID(string countryId)
{
int id = Convert.ToInt32(countryId);
var states = db.States.Where(d => d.CountryID == id).Select(e => new { e.UID, e.StateName }).ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCityByStateID(string stateId)
{
int id = Convert.ToInt32(stateId);
var Cities = db.Cities.Where(d => d.StateID == id).Select(e => new { e.UID, e.CityName }).ToList();
return Json(Cities, JsonRequestBehavior.AllowGet);
}
public ActionResult Update(int id)
{
CustomerManagement cc = db.CustomerManagements.Find(id);
ViewBag.CountryID = new SelectList(db.Countries.Where(d => d.CountryID.ToString() == cc.Country.ToString()), "CountryID", "CountryName",cc.CountryID);
var ucusmanvm = new UCustomerManagementViewModel();
ucusmanvm.UCountry = cc.Country;(here i get value 1)
ucusmanvm.UState = cc.State;(here i get value 2)
ucusmanvm.UCity = cc.City;(here iget value 2)
return View(ucusmanvm);
}
here i pass all the value to view form
My View Code
$(document).ready(function () {
debugger;
$.ajax({
type: "GET",
url: '#Url.Action("GetCountries", "FrmCustomerManagement")',
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCountry').append('<option value="' + value.CountryID + '">' + value.CountryName + '</option>');
});
}
});
$('#dropdownCountry').change(function () {
debugger;
$('#dropdownState').empty();
var cval = $('#dropdownCountry').val()
$.ajax({
type: "POST",
url: '#Url.Action("GetStatesByCountryID", "FrmCustomerManagement")',
datatype: "Json",
data: { countryId: cval },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownState').append('<option value="' + value.UID + '">' + value.StateName + '</option>');
});
}
})
});
$('#dropdownState').change(function () {
debugger;
$('#dropdownCity').empty();
var sval = $('#dropdownState').val()
$.ajax({
type: "POST",
url: '#Url.Action("GetCityByStateID", "FrmCustomerManagement")',
datatype: "Json",
data: { stateId: sval },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCity').append('<option value="' + value.UID + '">' + value.CityName + '</option>');
});
}
})
});
#Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { #class = "form-control", #width = "80%", #value=Model.UCountry})
<div class="col-sm-8">
<label>State</label>
#Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { #class = "form-control", #width = "80%" , #value=Model.UState})
</div>
<div class="col-sm-8">
<label>City</label>
#Html.DropDownList("dropdownCity", new SelectList(string.Empty, "Value", "Text"), "Please select a City", new { #class = "form-control", #width = "80%" , #value=Model.Ucity})
</div>
Here in update from also i acheive Cascading dropdown using ajax. but in update form i donno how to bring the save value to drop downs(Country city, state) from controller to view (eg i saved UAE in Country Dropdown but in edit mode i donno how to bring UAE value in Country dropdown ).I passed value from controller but i donno how to bind that value in view.please any one help me to resolve this issue .

How to pass 2 parameters through $.getJson in MVC?

I am doing my application in MVC. I did cascading dropdownlist in list . While selecting the value from dropdown i passed the value by $.getJson() to the controller. I am passing one id to the controller. My problem is i need to pass 2 id's to the controller. Is it possible to send 2 ids to the controller?
My View page is
<div>
#Html.DropDownList("Business", ViewBag.CategoryID as SelectList ,"Select the Business Category", new { id = "Business" })
</div>
<div>
<label>Select the Service Type</label>
#*<select id="Buname" name="buname" style="width:150px"></select>*#
#Html.DropDownList("Service", ViewBag.Service as SelectList,"Select", new { id = "Service", name ="buname"})
</div>
<div>
<label> Select the Location</label>
<select id="Location" name="location" style="width:150px"></select>
</div>
<div>
<label> Select the Location</label>
<select id="Employee" name="employee" style="width:150px"></select>
</div>
<script type="text/javascript">
$(function () {
$('#Business').change(function () {
$.getJSON('/Appt/Categories/' + $('#Business').val(), function (data) {
var items = '<option> Any Hospital</option>'
$.each(data, function (i, Service) {
debugger;
items += "<option value='" + Service.Value + "'>" + Service.Text +
"</option>";
});
$("#Service").html(items);
});
});
$('#Service').change(function () {
$.getJSON('/Appt/Location/' + $('#Service').val(), function (data) {
var items = '<option> Any Location </option>';
$.each(data, function (i, location) {
items += "<option value='" + location.Value + "'>" + location.Text +
"</option>";
});
$("#Location").html(items);
});
});
$('#Location').change(function () {
$.getJSON('/Appt/Employee/' + $('#Location').val(), function (data) {
var items = '<option> Any Employee </option>';
$.each(data, function (i, employee) {
items += "<option value='" + employee.Value + "'>" + employee.Text +
"</option>";
});
$("#Employee").html(items);
$("Service").html(items);
});
});
});
</script>
My Controller code is
public ActionResult WaitingList()
{
SYTEntities ca = new SYTEntities();
ViewBag.CategoryId = new SelectList(ca.BusinessCategories.ToList(), "CategoryId", "CategoryName");
ViewBag.Service = new SelectList(ca.tblBusinessCategories.ToList(), "BusinessID", "BusinessName");
return View();
}
public JsonResult Categories(int id)
{
SYTEntities db = new SYTEntities();
var business = from s in db.tblBusinessCategories
where s.CategoryId == id
select s;
return Json(new SelectList(business.ToArray(),"BusinessID", "BusinessName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Location(int id)
{
SYTEntities db = new SYTEntities();
var location = from s in db.tblBusinessLocations
where s.BusinessID == id
join loc in db.tblLocations
on s.LocID equals loc.LocationId
select loc;
return Json(new SelectList(location.ToArray(), "LocationId", "LocationName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Employee(int id)
{
SYTEntities db = new SYTEntities();
var emp = from s in db.Employees
where s.LocationId == id && s.BusinessID == 91
select s;
return Json(new SelectList(emp.ToArray(), "EmpId", "EmpName"), JsonRequestBehavior.AllowGet);
}
In public JsonResult Employee(int id) i need to pass ('#Service') value.
Is it possible to do? Can anyone please help me?
You can pass as many values as you want using the data parameter of jQuery.getJSON
var url = '#Url.Action("Categories", "Appt")'; // don't hard code your urls!
$.getJSON(url, { id: $('#Business').val(), otherProperty: anotherValue }, function (data) {
Yes you just need to add one more parameter to the Controller Action as below.
public JsonResult Categories(int id, int id2)
{
SYTEntities db = new SYTEntities();
var business = from s in db.tblBusinessCategories
where s.CategoryId == id
select s;
return Json(new SelectList(business.ToArray(),"BusinessID", "BusinessName"), JsonRequestBehavior.AllowGet);
}
and the below change in you View
$.getJSON('/Appt/Categories/' + $('#Business').val(), { id2: ('#otherId2').val() }, function (data) {
var items = '<option> Any Hospital</option>'
$.each(data, function (i, Service) {
debugger;
items += "<option value='" + Service.Value + "'>" + Service.Text +
"</option>";
});
$("#Service").html(items);
});

getting the error while copying feature ""Requested type name "feature" is unknown.""

This is code what I wrote for this...
Feature Deep Copy
rally.PortfolioItemDeepCopy = function (rallyDataSource, config) {
var portfolioitemBuffer = [];
var firstPortfolioItem = null;
var firstStory = null;
var finishedCallback;
var that = this;
//dojo.connect(obj, event, context, method, dontFix);
this._fireEvent = function(eventName, eventArgs) {
if (config && config.eventListeners[eventName] && dojo.isFunction(config.eventListeners[eventName])) {
config.eventListeners[eventName](that, eventArgs);
}
};
// removes private and read only fields to keep from pushing them up.
this.filterObject = function (object) {
return object;
};
this._addObject = function(object, typeName, callback) {
var item = dojo.clone(object);
item = this.filterObject(item);
function errorFunctionWrapper(error) {
if (dojo.isArray(error.Errors)) {
var errorMessage = error.Errors.pop();
if (errorMessage.indexOf("Not authorized to create:") >= 0) {
errorMessage = "Unable to create an object. This can happen due to a child or task being in a project you do not have write permissions to.";
}
rally.sdk.ui.AppHeader.showMessage("error", errorMessage, 10000);
}
else if(dojo.isObject(error)&&error.message){
rally.sdk.ui.AppHeader.showMessage("error", error.message, 10000);
error = [error.message];
}
if (dojo.isFunction(config.onError)) {
config.onError(error);
}
}
rallyDataSource.create(typeName, item, callback, errorFunctionWrapper);
};
this._copyAllFromBuffer = function() {
if (portfolioitemBuffer.length > 0) {
var portfolioitem = portfolioitemBuffer.pop();
that._copyPortfolioItem(portfolioitem.ref, portfolioitem.parent, that._copyAllFromBuffer);
}
else {
if (finishedCallback) {
finishedCallback(firstPortfolioItem);
}
}
};
this._addPortfolioItemsToBuffer = function(portfolioitemArray, parentRef) {
dojo.forEach(portfolioitemArray, function (portfolioitem) {
portfolioitemBuffer.push({
ref: portfolioitem._ref,
parent: parentRef
});
});
};
this._copyPortfolioItem = function(ref, parentRef, callback) {
rallyDataSource.getRallyObject(ref, function (foundObject) {
var type = "feature"
that._fireEvent("portfolioitemPreAdd", {portfolioitem:foundObject});
if (parentRef) {
foundObject.Parent = parentRef;
}
else {
foundObject.Name = "(Copy of) " + foundObject.Name;
}
that._addObject(foundObject, type, function (portfolioitemRef) {
if (!firstPortfolioItem) {
firstPortfolioItem = portfolioitemRef;
}
that._fireEvent("portfolioitemPostAdd", {});
that._addPortfolioItemsToBuffer(foundObject.Children, portfolioitemRef);
that._copyStoriesToPortfolioItem(foundObject.Stories, portfolioitemRef, callback);
that._copyTasksToStory(foundObject.Tasks, portfolioitemRef, callback);
}, null);
});
};
this._copyTasksToStory = function(tasks, storyRef, callback) {
//Copy the array
var localTasks = tasks.slice(0);
if (localTasks.length > 0) {
var task = localTasks.pop();
that._copyTask(task._ref, storyRef, function () {
that._copyTasksToStory(localTasks, storyRef, callback);
});
}
else {
callback();
}
};
this._copyStoriesToPortfolioItem = function(stories, portfolioitemRef, callback) {
//Copy the array
var localStories = stories.slice(0);
if (localStories.length > 0) {
var task = localStories.pop();
that._copyStory(story._ref, portfolioitemRef, function () {
that._copyStoriesToPortfolioItem(localStories, portfolioitemRef, callback);
});
}
else {
callback();
}
};
this._copyStory = function(ref, portfolioitemRef, callback) {
rallyDataSource.getRallyObject(ref, function (foundObject) {
var type = "hierarchicalrequirement";
foundObject.WorkProduct = portfolioitemRef;
that._fireEvent("storyPreAdd", {story:foundObject});
that._addObject(foundObject, type, function (ref, warnings) {
if (callback) {
that._fireEvent("storyPostAdd", [ref]);
callback();
}
}, null);
});
};
this._copyTask = function(ref, storyRef, callback) {
alert('helooooddddddddddddd task', ref);
rallyDataSource.getRallyObject(ref, function (foundObject) {
var type = "task";
foundObject.WorkProduct = storyRef;
that._fireEvent("taskPreAdd", {task:foundObject});
that._addObject(foundObject, type, function (ref, warnings) {
if (callback) {
that._fireEvent("taskPostAdd", [ref]);
callback();
}
}, null);
});
};
this.copyPortfolioItem = function (ref, callback) {
alert('hello');
that._copyPortfolioItem(ref, undefined, that._copyAllFromBuffer);
finishedCallback = callback;
};
};
</script>
<style type="text/css">
/* Add app styles here */
</style>
<script type="text/javascript">
rally.addOnLoad(function() {
var selectedValue = null;
var tasksAdded = 0;
var storiesAdded = 0;
var portfolioitemAdded = 0;
var searchPortfolioItem;
var searchStories;
var goButton, chooseButton;
var chooser;
var waiter;
var dataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
function taskPostAdd(object, args) {
tasksAdded = tasksAdded + 1;
displayTasksAdded(tasksAdded);
}
function taskPreAdd(object, args) {
dojo.byId("currentInfo").innerHTML = "Adding Task " + args.task.FormattedID + " - " + args.task.Name;
}
function storyPreAdd(object, args) {
dojo.byId("currentInfo").innerHTML = "Adding User Story " + args.story.FormattedID + " - " + args.story.Name;
}
function storyPostAdd(object, args) {
storiesAdded = storiesAdded + 1;
displayStoriesAdded(storiesAdded);
}
function displayStoriesAdded(count) {
dojo.byId("storyResult").innerHTML = "Stories added: " + count;
}
function portfolioitemPreAdd(object, args) {
dojo.byId("currentInfo").innerHTML = "Adding PortfolioItem " + args.story.FormattedID + " - " ;
}
function portfolioitemPostAdd(object, args) {
portfolioitemsAdded = portfolioitemsAdded + 1;
displayPortfolioItemsAdded(portfolioitemsAdded);
}
function displayPortfolioItemsAdded(count) {
dojo.byId("portfolioitemResult").innerHTML = "PortfolioItems added: " + count;
}
function displayTasksAdded(count) {
dojo.byId("taskResult").innerHTML = "Tasks added: " + tasksAdded;
}
function portfolioitemCopied(portfolioitem) {
dojo.byId("currentInfo").innerHTML = "Copy complete: ";
var link = new rally.sdk.ui.basic.Link({
item: portfolioitem,
text: portfolioitem._refObjectName
});
link.display('currentInfo');
goButton.setEnabled(true);
chooseButton.setEnabled(true);
if(waiter) {
waiter.hide();
waiter = null;
}
}
function buttonPressed() {
if (selectedValue) {
var config = {
eventListeners:{
portfolioitemPreAdd:portfolioitemPreAdd,
portfolioitemPostAdd:portfolioitemPostAdd,
storyPreAdd:storyPreAdd,
storyPostAdd:storyPostAdd,
taskPreAdd:taskPreAdd,
taskPostAdd:taskPostAdd
}
};
portfolioitemsAdded = 0;
displayPortfolioItemsAdded(portfolioitemsAdded);
tasksAdded = 0;
displayTasksAdded(tasksAdded);
storiesAdded = 0;
displayStoriesAdded(storiesAdded);
dojo.byId("currentInfo").innerHTML = "";
var copy = new rally.PortfolioItemDeepCopy(dataSource, config);
goButton.setEnabled(false);
chooseButton.setEnabled(false);
waiter = new rally.sdk.ui.basic.Wait({});
waiter.display('wait');
copy.copyPortfolioItem(rally.sdk.util.Ref.getRelativeRef(selectedValue), portfolioitemCopied);
}
}
function onChooserClose(chooser, args) {
if (args.selectedItem) {
selectedValue = args.selectedItem;
goButton.setEnabled(true);
dojo.byId('portfolioitemBox').innerHTML = args.selectedItem.FormattedID + ' - ' + args.selectedItem.Name;
}
}
function showChooser() {
var chooserConfig = {
fetch:"FormattedID,Name,Description",
type: "PortfolioItem",
title: "Feature Chooser"
};
chooser = new rally.sdk.ui.Chooser(chooserConfig, dataSource);
chooser.addEventListener('onClose', onChooserClose);
chooser.display();
}
rally.addOnLoad(function () {
goButton = new rally.sdk.ui.basic.Button({
text: "Copy",
enabled: false
});
goButton.addEventListener('onClick', buttonPressed);
goButton.display('goButton');
chooseButton = new rally.sdk.ui.basic.Button({
text: "Choose"
});
chooseButton.addEventListener('onClick', showChooser);
chooseButton.display('chooseButton');
showChooser();
rally.sdk.ui.AppHeader.setHelpTopic("252");
});
});
</script>
</head>
<body>
<div id="container">
<div style="float:left">
<span id="chooseButton"></span>
<span id="portfolioitemBox" style="line-height:18px;vertical-align:middle">[No feature selected]</span>
<span id="goButton"></span>
</div>
<div id="wait" style="float:left; height: 16px; width: 24px;"></div>
<div style="margin-left:5px;padding-top:10px;clear:both">
<div id="currentInfo" style="height:16px"></div>
<div id="portfolioitemResult" style="margin-top:10px"></div>
<div id="storyResult"></div>
<div id="taskResult"></div>
</div>
</div>
</body>
</html>
In WS API there is no object "feature". Please try either portfolioitem/feature or portfolioitem and then filter out by _type, e.g.
if(results.pi[i]._type == "PortfolioItem/Feature"){ //...
as shown here.
Since you are using a legacy AppSDK1 I assume you are setting a version to 1.43 as mentioned in this post.