Passing a JavaScript variable to a helper method - javascript

I am using ASP.NET MVC 3 and the YUI library.
I created my own helper method to redirect to an edit view by passing in the item's ID from the Model as such:
window.location = '#Url.RouteUrl(Url.NewsEdit(#Model.NewsId))';
Now I am busy populating my YUI data table and would like to call my helper method like above, not sure if it is possible because I get the item's ID by JavaScript like:
var formatActionLinks = function (oCell, oRecord, oColumn, oData) {
var newsId = oRecord.getData('NewsId');
oCell.innerHTML = 'Edit';
};

Store your URL with some custom ID, which you'll now to replace later on:
var myurl = '#Url.RouteUrl(Url.NewsEdit(0))'; //Let's use zero
later on:
var formatActionLinks = function (oCell, oRecord, oColumn, oData) {
var newsId = oRecord.getData('NewsId');
//lets use the url we defined above, and replace the zero with our id.
oCell.innerHTML = 'Edit';
};

Related

SAP OpenUI5 - SearchField break List template if a search string doesn't provides data

I'm developing a web application using SAP OpenUI5 framework.
I have an issue filtering data in a List table, with SearchField widget.
The SearchField is defined in xml view:
<SearchField id="taskSearchBox" enableClear="true" liveChange="onSearchTasks"></SearchField>
on my controller I've defined function called at every change in the SearchField:
onSearchTasks : function (oEvent) {
var self = this;
let searchField = 'Title';
let searchString = oEvent.getSource().getValue() ;
let oFilter = new Filter(searchField, sap.ui.model.FilterOperator.Contains, searchString);
self.getView().byId('tableTask').getBinding('items').filter([oFilter]);
},
Here's a GIF of my issue:
onSearchTasks : function (oEvent) {
var self = this;
let oFilter = "";
let searchField = 'Title';
let searchString = oEvent.getSource().getValue() ;
if(searchString) {
oFilter = new Filter(searchField,sap.ui.model.FilterOperator.Contains, searchString);
}
self.getView().byId('tableTask').getBinding('items').filter([oFilter]);
}
The control you're using is deprecated. You need to use sap.m.SearchField. I believe the error is because of the enableClear property of the deprecated field.
The issue was related to the creation of the binding, between model and Table items.
Code with issue:
let oTable = self.getView().byId('tableTask');
oTable.bindAggregation('items', {
path:'/rowsData', // field name of JSON object containing rowsData
template: oColumnsListItem, // rowTemplate of cells
});
Code without issue:
let oTable = self.getView().byId('tableTask');
oTable.removeAllItems();
oTable.removeAllAggregation();
oTable.bindAggregation('items', {
path:'/rowsData', // field name of JSON object containing rowsData
template: oColumnsListItem, // rowTemplate of cells
});
so adding these two lines of code:
oTable.removeAllItems();
oTable.removeAllAggregation();
solved the issue.
Honestly do not know if it's the correct way or just a workaround, but now everything is working.

Pasing Javascript result to View

I got a Question, I'm really new in working with Asp.net.
I got a Javascript where I woult like to pass Data to my Controller.
<script type="text/javascript">
$("#SearchButton").on("click", function () {
var $sucheMoped = [];
$("#tab_logic tbody tr")
.each(function () {
var $Item = $(this);
var suchfeld = $Item.find("td > input[name='Suchfeld']").val();
var schluessel = $Item.find("td > select[name='Suchschluessel'] > option:selected").val();
alert(suchfeld + "&&&" + schluessel);
$sucheMoped.push({
Suchfeld: suchfeld,
Suchschluesseltyp: schluessel
});
});
window.open('#Url.Action("MainView","MainView")?SuchObject='+$sucheMoped);
})
</script>
I just would like to pass the "sucheMoped" from my javaScript to my Controller.
My Controller is just expecting a IEnumarable of Objects with Properties Suchfeld and Suchschluesseltyp.
Anyone an idea?
Thanks Guys.
First of all, you need to change the way you invoke the controller action. You should stringify the array using the JSON.stringify() method.
So, this should look like this:
window.open('#Url.Action("MainView","MainView")?SuchObject='+JSON.stringify($sucheMoped));
Then, you need to create a custom model binder to bind your array with the action parameter. This is a simple array model binder for demonstration purposes only, it doesn't take into account failures or whatever, but it works in this scenario, passing the correct data, so please modify it to fit your needs.
public class ArrayModelBinder: DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var rawArray = controllerContext.HttpContext.Request.QueryString["SuchObject"];
var array = JsonConvert.DeserializeObject<IEnumerable<MyObject>>(rawArray);
return array;
}
}
What I do here, is to get the query string submitted through the URL, convert it with JsonConvert.Deserialize<T> method and return it.
You simply need to decorate your parameter in the controller's action with the custom model binder, like this:
[HttpGet]
public ActionResult Search([ModelBinder(typeof(ArrayModelBinder))]IEnumerable<MyObject> SuchObject)
{
return View(SuchObject);
}
Edit
window.open is useful if you want to open a new browser window. You could use it to open a new tab as well.
In order to navigate to another location without opening a new tab or window, use the window.location property like the following:
window.location = '#Url.Action("Search", "Home")?SuchObject=' + JSON.stringify(array);
If you use the jQuery.ajax method, you can pass complex objects as data parameter.
$.ajax({
url: '#Url.Action("MainView", "MainView")',
type: 'GET',
data: { 'SuchObject': $sucheMoped },
success: function (htmlContent) {
// write content to new window (from http://stackoverflow.com/a/23379892/1450855)
var w = window.open('about:blank', 'windowname');
w.document.write(htmlContent);
w.document.close();
}
});
You can use jquery library $.getScript to call the action method in your controller and the return javascriptResult type in your action.
$.getScript("Home","Display")
// Home Controller
private JavaScriptResult Display()
{
string message = "alert('Hello World');";
return new JavaScriptResult { Script = message };
}

ServiceNow UI Page GlideAjax

I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}

URL parameters on javascript

I´m making a call using javascript and I would like to send an array:
var selected = [];
selected=getAllEnginesIdsSelected();
console.log("selected: "+selected);
$.getJSON('/call/' + selected,
function(myList) {
The funcion that I use in Javascript to retrieve array is:
function getAllEnginesIdsSelected() {
var selected = [];
$("input:checkbox[id^='engine_']:checked").each(function(){
var ele=$(this)[0].id;
selected.push(ele);
});
return selected;
}
Console.log retrieves selected: 2,5
In MVC Controller I have
#RequestMapping(method = RequestMethod.GET, value = "/call/{selected}")
public List<List<myList>> myCall(#RequestParam(value="selected[]") String[] selected){
I gives an error. I don´t want to use AJAX. This is posible to send?
selected is an array, which you are joining to a string in the URL. Try something like $.getJSON('/call/?selected=[' + selected.join(',')]

how to pass params in remotefunction

I have a javascript function with remotefunction,,, in that remotefunction i want to pass map has parameter and i want to use that map variable in controller action,, i don't know how to pass that in params of ramotefunction and to use it in that particular controller action...
jQuery(document).ready(function(){
alert("checking for checkbox");
var countryId = document.getElementById("countryId").value;
jQuery('#groupdelete').on('click', function(){
var names = {};
alert("*********");
jQuery('input:checked').each(function() {
alert(jQuery(this).attr("id"));
if(jQuery(this).attr("id")) {
var id=jQuery(this).attr("id")
var costId = "c"+id
var ntb = document.getElementById(costId).value;
alert(ntb);
names[id] = ntb;
}
});
alert(names[1]);
})
${remoteFunction(action:'addLabServiceToCountry', controller:'country', params:'\'names=\'+names')}
})
params:'\'names=\'+names' which is not working properly, how to pass map variable in params of remotefunction and in contoller action how to access that.
Try this:
${remoteFunction({action: "addLabServiceToCountry", controller: "country", params: names});
Then in remoteFunction() you need to iterate through params to get all mapped names.
Or you can convert names to a string:
var namesStr = names.join(',');
and then pass the string:
${remoteFunction({... , params: namesStr});

Categories

Resources