Record is Not updated ASP.NET Ajax - javascript

I tried to update the data but it didn't update. Data is loaded into a datatable with edit and delete buttons, when I click edit button data will be passed in to the relevant textboxes for edit. I attached the screenshot below for easy to understand the problem. If I change the data and click the button data is not updated. Add and edit both things I do at one button.
Screenshot:
Edit button in the datatable code
"sTitle": "Edit",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-success"
onclick="get_category_details(' + mData + ') ">Edit</button>';
When I click the edit button it goes to the function get_category_details(id) along with record id and displayed records on relevant textboxes
function get_category_details(id) {
$.ajax({
type: 'POST',
url: 'edit_return.asmx/doSome',
dataType: 'JSON',
data: "{id: '" + id + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
$("html, body").animate({ scrollTop: 0 }, "slow");
isNew = false;
id = data.d[0].id
$('#fname').attr('value', data.d[0].fname);
$('#age').attr('value', data.d[0].age);
}
});
}
After I make changes and click the button, it is goes to Addproject() function
this is button. else part for record updated. This how I sent the record to update.aspx page I have two fields fname and age in the form with id means
id = data.d[0].id
This I send it
{fname: '" + $('#fname').val() + "',age: '" + $('#age').val() + "'}" + "&id=" + id,
look like this way any problem on that
<input type="button" id="b1" value="add" class="form-control" onclick="addProject()" />
Addproject() function
var isNew == true// if isNew == true means the record is new
if it is false mean update one existing record
function Addproject()
{
if (isNew == true) {
_url = 'insert.aspx/doSomething';
_data = "{fname: '" + $('#fname').val() + "',age: '" + $('#age').val() + "'}";
_method = 'POST';
}
else {
_url = 'update.aspx/doSomething',
_data = "{fname: '" + $('#fname').val() + "',age: '" + $('#age').val() + "'}" + "&id=" + id,
_method = 'POST';
}
$.ajax({
type: _method,
url: _url,
dataType: 'JSON',
contentType: "application/json; charset=utf-8",
data: _data,
success: function (data) {
// alert("success");
get_all();
var msg;
if (isNew = true)
{
alert("Data Added");
}
else
{
alert("Data Updated");
}
});
}
}
This is code for receiving the data and update the record at update.aspx
update.aspx
public class UserClass
{
public string fname { get; set; }
public int age { get; set; }
}
[WebMethod]
public static string doSomething(string fname, int age, int id)
{
SqlConnection con = new SqlConnection("server=.; Initial Catalog = jds; Integrated Security= true;");
string sql = "update record set name ='" + fname + "', age ='" + age + "' where id = '" + id + "')";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return "Success";
}

Related

How can i check User Role in javascript (without razor or controller)

I'm trying to use User.IsInRole() with javascript like on the razor page. I don't want use Controller, if this can be done, How can i do this in MVC5?
Edit: I want to display button by user role. I can do this with the razor page. There are fields in javascript where I add elements to the table, I will try to use them here.
You can do like below as shown below in for price
#{var price=20;}
<html>
<body>
#if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
try like this:
//Check login User has 'System Administrator' role
function CheckUserRole() {
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < currentUserRoles.length; i++) {
var userRoleId = currentUserRoles[i];
var userRoleName = GetRoleName(userRoleId);
if (userRoleName == "System Administrator") {
return true;
}
}
return false;
}
//Get Rolename based on RoleId
function GetRoleName(roleId) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
var roleName = null;
$.ajax(
{
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
roleName = data.d.results[0].Name;
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
}
);
return roleName;
}
https://msdynamicscrmblog.wordpress.com/2013/03/10/get-login-user-role-names-in-javascript-in-dynamics-crm-2011/

Dropdown's onchange is not triggered when selected value is set server side

I have a drop down list with a client side onchange that I use to populate a jQuery data table. If the value of another drop down is changed and on server side I repopulate the first drop down and set its selected value, its onchange is not triggered and data table not updated with new data.
$(document).on('change', '#ddlFacility', function () {debugger
var facilityID = this.value;
if (facilityID > -1) {
var facCertUrl = "services/easg.asmx/GetSomethingByFacilityID";
var facCertParams = "{ 'FacilityID': '" + facilityID + "', 'Date': '" + $("#hfStartDate").val() + "' }";
populteTable(facCertUrl, facCertParams, tblFacCert);
}
});
function populteTable(ws_url, parameters, table) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: ws_url,
cache: false,
data: parameters,
}).done(function (result) {debugger
table.clear().draw();
if (!result || result.d === "") {
$('#divGrid').hide();
}
else {
jResult = JSON.parse(result.d);
table.rows.add(jResult).draw();
table.columns([4, 5, 6, 7, 8, 9, 10, 11]).visible(false);
$('#divGrid').show();
}
}).fail(function (jqXHR, textStatus, errorThrown) {debugger
$('#divGrid').hide();
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
}
var tblFacCert = $("#fcTable").DataTable({
....
});
Server side, when second drop down's value is changed:
protected void ddlDistrict_SelectedIndexChanged(object sender, EventArgs e)
{
string sFacID = somehow_get_FacID();
ListItem li = ddlFacility.Items.FindByValue(sFacID);
if (null != li)
{
li.Selected = true; // This does not trigger onchange
// This changes the selection and runs the onChange() event; but data table is now empty!
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "ddlFacility", "$(\"#ddlFacility\").val(\"" + li.Value + "\").change();", true);
}
}

How to pass a dataTable from C# code behind to jQuery

I have string to pass as a table of data from C# code behind to jQuery.
for that I am using two functions:
C#
[System.Web.Services.WebMethod(EnableSession = true)]
public static List<ListItem> GetImageArray(string AccNo)
{
string result = string.Empty;
var obj = new AccountTransaction();
DataTable dt = obj._commonobj.SearchAccNo(AccNo, "", "GETIMAGE");
List<ListItem> datas = new List<ListItem>();
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
string CustImg = Convert.ToString(row["Customer Image"]);
string SignImg = Convert.ToString(row["Sign"]);
ListItem listitem = new ListItem(CustImg, SignImg);
datas.Add(listitem);
}
}
return datas;
}
Client-side
$.ajax({
type: "POST",
url: "AccountTransaction.aspx/GetImageArray",
data: "{'AccNo':'" + col1 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnImgSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnImgSuccess(response) {
alert(response.d);
});
}
return datas; returns 2 row and alert(response.d) is not showing anythig
I tried using $.map(data, function (listitem) function but no result .
$.map(data, function (listitem) {
$('<tr> <td>' + listitem.CustImg + '</td> <td>' + listitem.SignImg + ' </td> </tr>').appendTo(".tblData");
});
Please help .!
Your array is there in the d property, so you can use the map function but using the data.d instead of just data.
Then the ListItem properties are Text and Value, so your code should look like this:
$.ajax({
type: "POST",
url: "AccountTransaction.aspx/GetImageArray",
data: "{'AccNo':'" + col1 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onImgSuccess,
failure: function (response) {
alert(response.d);
}
});
function onImgSuccess(data) {
$.map(data.d, function (listitem) {
$('<tr> <td>' + listitem.Text + '</td> <td>' + listitem.Value + ' </td> </tr>').appendTo(".tblData");
});
}
Use the following code.
alert($.parseJSON(response.d));

How can I pass jquery variable as parameter to Java controller by href?

This is my variable in javascript:
var dataid = dataInfo[i];
I want to pass the variable to my java controller through href:
row = row + "<tr><td>" + dataid + "</td><td>" +
schoolid + "</td><td>" +
"<td><a class='details' id='" + dataid + "' href='#{DataManagement.dataDetails(dataId)}'>Details</a></td>"+
"<td>"+
</tr>";
but controller gets null value.
I am trying this using ajax:
$.ajax({
type: "GET",
url: "#{DataManagement.dataDetails}",
data: {
id: dataId
},
success: function(data) {
console.log(data);
}
});
This is my controller:
public static void dataDetails(Long id) throws SQLException {
Logger.info("id: "+ id);
//dataId=dataId.trim();
//Long iid = Long.parseLong(dataId);
Data data = Data.findById(id);
String totalStudent = Data.getTotalStudent(1L);
Logger.info("totalStudent: " + totalStudent);
renderArgs.put("totalStudent",totalStudent);
render(data,totalStudent);
}
But after ajax call it is not render the new page.
How can I do this?
It works!!!
I changed it to :
<td><a class='details' id='" + dataid + "' href='/datamanagement/dataDetails/"+dataid+"'>Details</a></td>
You can send a json request with ajax and accept it on Controller.
Ajax Request:
$.ajax({
type: "POST",
contentType: "application/json",
data: JSON.stringify(yourObject),
url: "/path",
success: function (msg) {
console.log(msg);
window.location = "/redirectTo";
},
error : function(e) {
console.log('Error: ' + e);
}
});
On Controller:
#ResponseBody
#CrossOrigin #RequestMapping(value = "/path", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
private ResponseEntity<YourObject> someMethod(#RequestBody YourObject obj){
// do your coding here
return new ResponseEntity<YourObject>(modifiedObject, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<YourObject>(HttpStatus.BAD_REQUEST);
}
}

JQuery autocomplete with using handler

I' m trying to create a search box with autocomplete property and using a handler.
I got all words from database but can not show them.
It' s jquery part:
$(function () {
$("#search-box").autocomplete({
source: "KeywordHandler.ashx",
minLength: 1,
#*select: function (event, ui) {
alert(ui.item.id + " / " + ui.item.value);
}*#
});
});
It' s handler part:
public class KeywordHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string prefixText = context.Request.QueryString["term"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Keyword from [dbo].[Log] where " + "Keyword like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["Keyword"])
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
At handler, I can get all the words which I need but can not show them as offered keywords at search box.
Is there any idea?
You may use something like below. Pay attention to "refresh" part. You should return your query result as JSON from webservice and then parse it. After parse, you can create list item for every search result item as I indicated in JQuery code (the last part of the code).
*I wrote my answer as supposing you are getting the result from your service properly.
HTML
<div id="assignDiv" style="display:none;">
<div data-demo-html="true" data-demo-js="true" data-demo-css="true">
<h3>Select contact:</h3>
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Search contact..." data-filter-theme="d"></ul>
</div>
<input type="button" value="Send to selected contact" id="assignToBtn" />
</div>
JQuery
$("#autocomplete").on("listviewbeforefilter", function (e, data) {
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
if (value && value.length > 2) {
$ul.html("<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>");
$ul.listview("refresh");
$.ajax({
type: "POST",
crossDomain: true,
url: serverAddress + "General.asmx/AutoComplete",
data: "{'q': '" + $input.val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.then(function (response) {
var JsonObj = jQuery.parseJSON(response.d);
$.each(JsonObj, function (i, val) {
html += "<li><a href='javascript:changeAutoCompleteText(\"" + val + "\");'>" + val + " <i style='color:grey;font-weight:lighter;'>(</i><i style='text-decoration:underline;color:grey;font-weight:lighter;'>" + val + "</i><i style='color:grey;font-weight:lighter;'>)</i></a></li>";
});
$ul.html(html);
$ul.listview("refresh");
$ul.trigger("updatelayout");
});
}
});

Categories

Resources