i am creating a web app with the help of angularjs,
on one of my button click i am calling a web service through angularjs
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public void getuprec(string id)
{
List<object> selectrecd = new List<object>();
SqlCommand cmd = new SqlCommand("select * from erp_admin.CompanySonVinUnitVenueRpt where comsonvinid in (select id from companysonvinunitvenue where id='"+id+"')",con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
selectrecd.Add(new
{
attendee1 = dr["comattendee1"].ToString(),
attendee2 = dr["comattendee2"].ToString(),
totalmale = dr["attendeetotalmale"].ToString(),
totalfemale = dr["attendeetotalfemale"].ToString(),
unit1 = dr["unitattendee1"].ToString(),
unitd1 = dr["unitattendee1desig"].ToString(),
unit2 = dr["unitattendee2"].ToString(),
unitd2 = dr["unitattendee2desig"].ToString(),
unit3 = dr["unitattendee3"].ToString(),
unitd3 = dr["unitattendee3desig"].ToString(),
unit4 = dr["unitattendee4"].ToString(),
unitd4 = dr["unitattendee4desig"].ToString(),
unit5 = dr["unitattendee5"].ToString(),
unitd5 = dr["unitattendee5desig"].ToString(),
remarks = dr["remarks"].ToString()
});
}
con.Close();
var json = js.Serialize(selectrecd);
Context.Response.Write("{" + '"' + "selectrecd" + '"' + ":" + json + "}");
}
this is my webservice which is working fine (i tested) and my angularjs file
$scope.updatefunction = function (param) {
$http.get('/frmattendencerptqed.asmx/getuprec', {
params: {
id: $scope.updateparam.comsonvinid
}
})
.then()
{
}
}
this is my angularjs
this is my input field
<input type="text" ng-model="remarks" style="width:100%;" />
now i need to take the previous value from my database and bind the value on my textbox, and if user edit the textbox then the value must be updated on button click
how i need to do this
this is my input field
<input type="text" ng-model="remarks" style="width:100%;" />
now i need to take the previous value from my database and bind the
value on my textbox, and if user edit the textbox then the value must
be updated on button click
Which one remarks property ?
In your webservice you returns a json object which contains a array of structured objects which each one may contain a remark property.
Can you post the resulted json of webservice call in order to give us more details ?
About how to retrieve and bind the data in your angular js controller, here is my answer.
From https://docs.angularjs.org/api/ng/service/$http
you can retrieve response from data property in returned object.
data – {string|Object} – The response body transformed with the
transform functions.
So you can do something like that:
$scope.updatefunction = function (param) {
$http.get('/frmattendencerptqed.asmx/getuprec', {
params: {
id: $scope.updateparam.comsonvinid
}
})
.then(
// handling if ok
function(response){
$scope.remarks=response.data.selectrecd[indexYourWish].remarks
},
function(errResponse){
// handling if error
return $q.reject(errResponse);
}
);
}
As explains previously, I refer to an array to retrieve the information in response.data with an index you should define or not use at all index if you don't return a array.
remarks should be a variable in the scope of your controller.
The more relevant syntax to use for controller depends on how you declare things in Angular (Personally, I avoid $scope.xxx syntax).
Post more of your JS code if you want a more precise answer.
It's just how angularjs normally works, the two way databinding follow this tutorial:
http://www.w3schools.com/angular/angular_databinding.asp
you'll see that what you only need is to call the update function from your controller and pass it the variable you bind to the input.
Of course this variable assigned to $scope or to this in the controller (there are two ways).
Related
called by selectbox go into function 'getDepAndMan()',
there is a value taken from the selectbox (works)
calls functions in the controller 'GetDepartmentAndManager' (works)
controller returns value (works)
{Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable<<>f__AnonymousType6<'string, string>>}
Result View: [0] { UserDepartament = "there is value here / string", UserManager = "there is value here / string" }
should go back to ajax and call 'succes: function (employee data)' (works)
should assign values to the fields (doesn't work)
show an alert (work)
show alert with values (doesn't work, show an alert with: undefined undefined)
View:
#(Html
.DevExtreme()
.SelectBox()
.DataSource(d => d
.Mvc()
)
.OnValueChanged("getDepAndMan")
)
#(Html.DevExtreme().TextBox()
.ID("Id_department")
.ReadOnly(true)
)
#(Html.DevExtreme().TextBox()
.ID("Id_manager")
.ReadOnly(true)
)
<script type="text/javascript">
function getDepAndMan() {
var userId = {
nazwaValueId: $("#idName").dxSelectBox("instance").option("value")
};
$.ajax({
url: "#Url.Action("GetDepartmentAndManager", "Uzytkownicy")",
type: "POST",
dataType: "json",
data: {"userId": JSON.stringify(userId)},
cache: false,
success: function (danePracownika) {
$("#Id_department")
.dxTextBox("instance")
.option("value", danePracownika.UserDepartament);
$("#Id_manager")
.dxTextBox("instance")
.option("value", danePracownika.UserManager);
alert(danePracownika.UserDepartament + " " + danePracownika.UserManager);
},
failure: function (error) {
alert(error);
},
error: function (error) {
alert(error);
}
});
}
</script>
Controller:
[HttpPost]
public ActionResult GetDepartmentAndManager(string userId)
{
dynamic serializer = JsonConvert.DeserializeObject<IDictionary>(userId);
var IdCzlowieka = serializer["nazwaValueId"];
int IntIdCzlowieka = Convert.ToInt32(IdCzlowieka);
var danePracownika = _uzytkownicyContext.Uzytkownicy.Where(x => x.Id == IntIdCzlowieka).Select(s => new
{
UserDepartament = s.Departament,
UserManager = s.ManagerLogin
});
return Json(danePracownika);
}
return : //
[0] { UserDepartament = "there is value here / string", UserManager = "there is value here / string" }
EDIT
The question is, what's wrong with the code, why it doesn't work for me?
.
I see that in Your GetDepartmentAndManager You are not using Your passed parameter userID:
var danePracownika = ... .Where(x => x.Id == IntIdCzlowieka)...
should be Where(x => x.Id == userId) instead.
The next thing that came to me is the value You are acctualy getting inside the controller action; based on the JS code I would say that this is not the ID of the employee what You are passing but the stringified object { "nazwaValueId": ... } that in the best case would be handled by the server and You will get the raw string as a value of userId (unless You have defined a IModelBinder class that would handle conversion from stringified { "nazwaValueId": ... } to the value of that field - more on that You can find here).
Oh any by the way - please try to avoid mixing languages. I have a friend in the company which was forced to work with the german project and all their code was written in German - You would DEFINETLY won't be happy working with it. But if this a project made only by PL for PL, that is some kind of acceptable approach I assume.
Also I highly advice You to not use HTTP POST method for getting data. To make long story short there is a convention that GET requests are for getting the data and You can call it as many times You like without affecting the state (było takie mądre słowo na to, ale nie pamiętam ;)) and POST is for saving/modifing data and should always redirect to GET method on return. You can read more about it here.
EDIT:
Ok, for some reason I have found that the call in the current form is sending data not as a body but as a form. I don't know, I don't use jQuery. But here is the reqest:
so I changed the signature of the action to
public ActionResult GetDepartmentAndManager([FromForm]string userId)
to get is started working. Maybe on Your side it is just working fine, I don't know. But what I have found is that while sending the responce to the client we end up with... this:
so as You can see either Ajax or server changed the JSON keys to be kebabCase not PascalCase and that's why You are getting undefined values. Because properties You arereading do not exists. Just check it out: alert(danePracownika.userDepartament + " " + danePracownika.userManager);
UPDATE:
I checked it, it was not server's fault:
I have a Kendo Grid on the start page of a .NET Core 2.0 MVC web app. The data source is populated via ViewData on page load:
public IActionResult Index()
{
var allForms = formsDB.FormHeader.Select(x => x);
ViewData["AllForms"] = allForms;
<...>
return View();
}
The data source object (FormHeader) contains a column with an employee code. One of the columns in my Kendo grid is currently displaying the employee code, but I'd like to display the full name via .ClientTemplate:
#(Html.Kendo().Grid<Forms.Models.FormHeader>()
.Name("HeadersMasterGrid")
.BindTo((IQueryable<Forms.Models.FormHeader>)ViewData["AllForms"])
.Pageable()
.Columns(columns =>
{
columns.Bound(p => p.EmployeeCode).Title("Employee")
/*.ClientTemplate("#=getEmployeeName(EmployeeCode)#")*/;
<..>
I'd like to display the employee's first and last name instead of the code. I set up an IAction result in my Form Controller to receive an employee code and return the full name (via ~/Form/GetEmployee/):
public ActionResult GetEmployee(string id)
{
var employee = theDB.EmployeeMasters.FirstOrDefault(x => x.EmployeeCode.Trim() == id.ToUpper());
BasicEmployee basicEmployee = new BasicEmployee(employee.FirstName, employee.LastName, id.Trim());
//return Json(basicEmployee);
return Json(basicEmployee.FullName);
}
Lastly, I added some jQuery script to my view that I was hoping would open the URL, retrieve the full name, and return that into the .ClientTemplate of the Kendo Grid column. You can see that I have tried returning just the full name, but also returning the entire object and then parsing/returning the full name from the object.
The second function in the block below was my most recent attempt after receiving some instruction about promises/callbacks (which are still pretty fuzzy).
#*function getEmployeeName(empCode) {
$.getJSON('#Url.Action("GetEmployee", "Form")' + "/" + empCode,
function(data) {
//var response = $.parseJSON(data);
//return response.FullName.toString();
return $.parseJSON(data);
}, 'json');
}*#
function getEmployeeName(empCode) {
var promise = $.getJSON('#Url.Action("GetEmployee", "Form")' + "/" + empCode);
$.when(promise).done(function(data) {
return JSON.stringify(data);
});
}
I've spent quite a bit of time with the Kendo docs, Google, and two Slack workspaces for developers, but I'm not finding anything that works. I have no experience with either Javascript or jQuery before this project and am still very much in the learning phase. I understand that I am most likely going about this incorrectly (or missing an easy solution), but I'd like to know how I can accomplish this.
Hi I am trying to get all documents library only created by the logged users. With the following code I get also libraries which was not created from a user. Thank you.
function GetAllLibraries() {
var listCollection = lists.getEnumerator();
while (listCollection.moveNext()) {
var listName = listCollection.get_current().get_title('Title');
document.getElementById('leftDiv').innerHTML += "<b>" + listName + "<b/>" + "<br />";
}
}
Since you are utilizing SharePoint JavaScript API (a.k.a JSOM) it is a bit tricky since SP.List object does not expose Author property to determine who created this object. But the good news that Author property could be extracted from SP.List.schemaXml property as demonstrated below
Here is a complete example how to retrieve lists created by current user
var ctx = SP.ClientContext.get_current();
var allLists = ctx.get_web().get_lists();
var currentUser = ctx.get_web().get_currentUser();
ctx.load(allLists,'Include(SchemaXml)');
ctx.load(currentUser);
ctx.executeQueryAsync(
function(){
var lists = allLists.get_data().filter(function(list){
var listProperties = schemaXml2Json(list.get_schemaXml());
var listAuthorId = parseInt(listProperties.Author);
return listAuthorId == currentUser.get_id();
});
console.log("The amount of lists created by current user: " + lists.length);
},
logError);
}
function schemaXml2Json(schemaXml)
{
var jsonObject = {};
var schemaXmlDoc = $.parseXML(schemaXml);
$(schemaXmlDoc).find('List').each(function() {
$.each(this.attributes, function(i, attr){
jsonObject[attr.name] = attr.value;
});
});
return jsonObject;
}
function logError(sender,args){
console.log(args.get_message());
}
If you want to know who created list or library, you need to get property SPList.Author. As i know, you can't get it by JSOM.
My advice for you is to develop your own http hanlder with logic on server-side and call it by ajax. For example, you pass arguments into handler like web url (_spPageContextInfo.webAbsoluteUrl), current user login or id (_spPageContextInfo.userId), and in handler iterate lists on web, compare current user and list creator. Finally, return needed lists info.
Or just develop web part and do the same: iterate lists and compare it with SPContext.Current.Web.CurrentUser
UPDATE:
Example of c# code. You can put it in your web part or event handler. In this code we iterate all lists on SPWeb and save lists title created by current user.
private void GetLists()
{
using (SPSite site = new SPSite("{site_url}"))
{
using (SPWeb web = site.OpenWeb())
{
SPListCollection listCol = web.Lists;
List<string> currentUserLists = new List<string>();
foreach(SPList list in listCol)
{
if (list.Author.ID == SPContext.Current.Web.CurrentUser.ID)
{
currentUserLists.Add(list.Title);
}
}
}
}
}
I need to get an attribute value ("val_index") of an entity which is selected in lookup.
function onLookupChange(){
var entityName, entityId, entityLabel, lookupFieldObject;
lookupFieldObject = Xrm.Page.data.entity.attributes.get('my_attribute');
if (lookupFieldObject.getValue() != null) {
entityId = lookupFieldObject.getValue()[0].id;
entityName = lookupFieldObject.getValue()[0].entityType;
entityLabel = lookupFieldObject.getValue()[0].name;
}
// here I need to get an attribute value of a selected entity. Attribute's name is "val_index"
}
How can I do that?
Use the SDK.REST.js library which ships with the CRM SDK to do this. Include this as a script in your form entity and you can reference the functions to make REST calls.
An example call might look like this:
// Assume we are working with the account entity.
// This call is asynchronous.
SDK.REST.retrieveRecord(entityId, "Account", "val_index", null,
// Success.
function (result) {
var value = result.val_index;
// Do something.
},
// Error retrieving the value.
function (error) {
// Notify the user...
});
I'm trying to convert my basic crud operations into an API that multiple components of my application can use.
I have successfully converted all methods, except the update one because it calls for each property on the object to be declared before the put request can be executed.
controller
$scope.update = function(testimonial, id) {
var data = {
name: testimonial.name,
message: testimonial.message
};
dataService.update(uri, data, $scope.id).then(function(response) {
console.log('Successfully updated!');
},
function(error) {
console.log('Error updating.');
});
}
dataService
dataService.update = function(uri, data, id) {
var rest = Restangular.one(uri, id);
angular.forEach(data, function(value, key) {
// needs to be in the format below
// rest.key = data.key
});
// needs to output something like this, depending on what the data is passed
// rest.name = data.name;
// rest.message = data.message;
return rest.put();
}
I tried to describe the problem in the codes comments, but to reiterate I cannot figure out how to generate something like rest.name = data.name; without specifying the name property because the update function shouldn't need to know the object properties.
Here is what the update method looked like before I started trying to make it usable by any of my components (this works)
Testimonial.update = function(testimonial, id) {
var rest = Restangular.one('testimonials', id);
rest.name = testimonial.name;
rest.message = testimonial.message;
return rest.put();
}
How can I recreate this without any specific properties parameters hard-coded in?
Also, my project has included lo-dash, if that helps, I don't know where to start with this problem. Thanks a ton for any advice!
Try like
angular.extend(rest,testimonial)
https://docs.angularjs.org/api/ng/function/angular.extend