Not getting a list of table in ajax array - c#

Can anybody tell me where I am wrong. I used this sample code in my other project, it's working fine but in my current project when I use this, it's just fetching first values from array but I want to get all the list values from array! So I hope you understand what I am saying. If you need to ask something more about this please comment.
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function () {
var degree = $(".txtcourse").val();
var institute = $(".txtinstitute").val();
var title = $(".txttitle").val();
var from = $(".fromdate").val();
var to = $(".todate").val();
$("tbody").append("<tr>" + "<td>" + degree + "</td>" + "<td>" + institute + "</td>" + "<td>" + title + "</td>" + "<td>" + from + "</td>" + "<td>" + to + "</td>" + + "<td>" + "<td><button name='record' type='button'><i class='fa fa-trash fa-sm'></i></button></td>" + "</tr>");
});
//$("button").click(function () {
// $("tbody").find('input[txtcourse="record"]').each(function () {
// $(this).parents("tr").remove();
// });
//});
$("#eduadd").on("click", function () {
debugger;
var txtcourse = Array();
var txtinstitute = Array();
var txttitle = Array();
var fromdate = Array();
var todate = Array();
$(".txtcourse").each(function (i, v) {
txtcourse.push($(this).val());
});
$(".txtinstitute").each(function (i, v) {
txtinstitute.push($(this).val());
});
$(".txttitle").each(function (i, v) {
txttitle.push($(this).val());
});
$(".fromdate").each(function (i, v) {
fromdate.push($(this).val());
});
$(".todate").each(function (i, v) {
todate.push($(this).val());
});
var postData = {
course: txtcourse, institute: txtinstitute, title: txttitle, frmdate: fromdate, tdate: todate
};
$.ajax({
type: "POST",
url: "/GuardEduaction/SaveEducation",
data: postData,
success: function (data) {
alert("saved");
},
error: function (data) {
alert("Error");
},
dataType: "json",
traditional: true });
});
});
</script>

Related

How to append Ajax.ActionLink in the table body using jquery?

Here is my ajax code:
<script>
$(document).ready(function () {
$("#BtnSearch").click(function () {
var SearchBy = $("#SearchBy").val();
var SearchValue = $("#Search").val();
var SetData = $("#DataSearching");
SetData.html("");
debugger;
$.ajax({
type: "POST",
contentType: "html",
url: "/SelectDeal/GetSearchingData?SearchBy=" + SearchBy + "&SearchValue=" + SearchValue,
success: function (result) {
debugger;
if (result.length == 0) {
SetData.append('<tr style="color:red"><td colspan="3">No Match Data</td></tr>');
}
else {
$.each(result, function (i, item) {
//var clientName = item.
var DealDateString = item.Deal_Date;
var valDealDate = new Date(parseInt(DealDateString.replace(/(^.*\()|([+-].*$)/g, '')));
var finalDealDate = valDealDate.getMonth() + 1 + "/" + valDealDate.getDate() + "/" + valDealDate.getFullYear();
var ValidityDateString = item.Validity_Date;
var valValidityDate = new Date(parseInt(ValidityDateString.replace(/(^.*\()|([+-].*$)/g, '')));
var finalValidityDate = valValidityDate.getMonth() + 1 + "/" + valValidityDate.getDate() + "/" + valValidityDate.getFullYear();
var val = "<tr>" +
"<td>" + finalDealDate + "</td>" +
"<td>" + item.Total_Amount_Remaining + "</td>" +
"<td>" + item.Dealer_Name + "</td>" +
"<td>" + finalValidityDate + "</td>" +
"<td>" + item.Location + "</td>" +
"<td>" + item.Deal_Amount + "</td>" +
"<td>" + #Ajax.ActionLink("Recieve payment", "myAction", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
}) + "</td>" +
"</tr>";
SetData.append(val);
});
}
},
error: function (data) {
alert(data);
}
});
});
});
</script>
I want to append Ajax.ActionLink in the setData variable which is actually a <tbody> element. It is not working. However, If I remove #ajax.actionLink from the above code, it works perfectly fine. Is there any way I can solve this problem?
If you look at the view source of the page, you can see that the current code will generate code like this
"<td>" + <a data-ajax="true" data-ajax-method="GET"
That is invalid because it looks like we are trying to concatenate the string "<td>" to a variable starts like <a ! , hence causing the issue.
You do not need any string concatenation. Use the output rendered by your C# code(call to the Ajax.ActionLink method) inside the td.
The Ajax.ActionLink method will render markup like below where you have double quotes for the attribute values. So you should use single quotes for your string concatenation operator (to val variable)
<a data-ajax="true" data-ajax-method="GET"
This should work.
'<td>#Ajax.ActionLink("Recieve payment", "Ajax.ActionLink", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
}) </td>' +

Why does the data come back as undefined?

I'm not understanding why the data is coming back as undefined. It knows there is something there but the value is not being shown. Am I forgetting to do something in the main function? Thanks in advance to whom may solve my dilemma.
Here is the current output I'm getting:
Here is what I need the output to render:
Here is the code for my employee.js:
$(function() {
ajaxCall("Get", "api/employees", "")
.done(function (data) {
buildTable(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
}); // ajaxCall
});
// build initial table
function buildTable(data) {
$("#main").empty();
var bg = false;
employees = data; // copy to global var
div = $("<div id=\"employee\" data-toggle=\"modal\"data-target=\"#myModal\" class=\"row trWhite\">");
div.html("<div class=\"col-lg-12\" id=\"id0\">...Click Here to add</div>");
div.appendTo($("#main"));
$.each(data,function(emp){
var cls = "rowWhite";
bg ? cls = "rowWhite" : cls = "rowLightGray";
bg = !bg;
div = $("<div id=\"" + emp.Id + "\" data-toggle=\"modal\" data-target=\"#myModal\" class=\"row col-lg-12" + cls + "\">");
var empId = emp.Id;
div.html(
"<div class=\"col-xs-4\" id=\"employeetitle" + empId + "\">" + emp.Title + "</div>" +
"<div class=\"col-xs-4\" id=\"employeefname" + empId + "\">" + emp.Firstname + "</div>" +
"<div class=\"col-xs-4\" id=\"emplastname" + empId + "\">" + emp.Lastname + "</div>"
);
div.appendTo($("#main"));
}); // each
} // buildTable
function ajaxCall(type, url, data) {
return $.ajax({// return the promise that '$.ajax' returns
type: type,
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true
});
}
Here is my Controller method code:
// GET api/<controller>
[Route("api/employees")]
public IHttpActionResult Get()
{
try
{
EmployeeViewModel emp = new EmployeeViewModel();
List<EmployeeViewModel> allEmployees = emp.GetAll();
return Ok(allEmployees);
}
catch(Exception ex)
{
return BadRequest("Retrieve failed - " + ex.Message);
}
}
The first parameter of the callback is the index, the value is in the second parameter:
$.each(data,function(index, emp){

How to bind asp.net grid view using jquery

I am trying to bind data into grid view using jquery. data is succesfully loaded in "result" but can not apply this data in grid view
My Script:
$(document).ready(function() {
$.ajax({
url: '../_AJAX/ajaxCall-InterestSubsidy.aspx',
data: { 'MODE': 'BindGrid' },
type: 'POST',
dataType: 'json',
success: function(result) {
var reslk = result;
$.each(result.Table1, function(index, res) {
$(".GridView1").append("<table><tr><td>" + res.StateId +
"</td><td>" + res.StateName +
"</td></tr></table>");
});
},
error: function(e) {
}
});
});
My grid view:
<asp:GridView ID="GridView1" runat="server" CssClass="GridView1">
</asp:GridView>
try this
$.map(result.d, function (item) {
$(".GridView1").append("<tr><td>" + item.StateId +
"</td><td>" + item.StateName +
"</td></tr>");
});
or
$.map(result.Table1, function (index, res) {
$(".GridView1").append("<tr><td>" + res.StateId +
"</td><td>" + res.StateName +
"</td></tr>");
});

Passing a parameter through AJAX but displayed null in the MVC method

I new with MVC and I'am trying to display a method with AJAX. The problem is that the parameter that I am passing into the method is display to be null, but when I debug the ajax code the parameter is not null. I don't know what I'm doing wrong.
This is my c# method
public JsonResult AllAccountList(int accountID)
{
Client myClient = new AccountServiceClient().GetClientByUsername(System.Web.HttpContext.Current.User.Identity.Name);
IEnumerable<Account> myAccounts = new AccountServiceClient().GetAccountWithClient(myClient.ClientID);
List<AccountModel> myList = new List<AccountModel>();
foreach (Account a in myAccounts.Where(a => a.AccountID == Convert.ToInt32(accountID)))
{
myList.Add(new AccountModel() { AccountID = a.AccountID,TypeID_FK = a.TypeID_FK, FriendlyName = a.FriendlyName, Currency = a.Currency, AvailableBalance = a.AvailableBalance});
}
return Json(myList, JsonRequestBehavior.AllowGet);
}
and this is my AJAX
function btnSelectClicked(AccountID) {
var params = '{"accountID":"' + AccountID + '"}';
$.ajax({
type: "POST",
url: "/Account/AllAccountList",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var gridview = "<table>";
gridview += "<tr><td id='titleCol'>AccountId</td><td id='titleCol'>Account Type</td><td id='titleCol'>Friendly Name</td><td id='titleCol'>Currency</td><td id='titleCol'>Available Balnce</td></tr>";
for (var i = 0; i < data.length; i++) {
gridview += "<tr><td>" + data[i].AccountID +
"</td><td>" + data[i].TypeID_FK +
"</td><td>" + data[i].FriendlyName +
"</td><td>" + data[i].Currency +
"</td><td>" + data[i].AvailableBalance + "</td></tr>";
}
gridview += "</table>";
$("#display2").html(gridview);
},
error: function (xhr,err) {
alert(xhr.responseText + "An error has occurred during processing your request.");
}
});
};
Try changing
var params = '{"accountID":"' + AccountID + '"}';
to
var params = {accountID: AccountID };
And see if that helps
UPDATE:
I didn't expect that to complain about a function... granted when ever I use the jquery ajax methods I use the specific one I need rather than the root ajax() method. Try this maybe.
function btnSelectClicked(AccountID) {
var params = {accountID: AccountID };
$.post("/Account/AllAccountList", data, function(data) {
var gridview = "<table>";
gridview += "<tr><td id='titleCol'>AccountId</td><td id='titleCol'>Account Type</td><td id='titleCol'>Friendly Name</td><td id='titleCol'>Currency</td><td id='titleCol'>Available Balnce</td></tr>";
for (var i = 0; i < data.length; i++) {
gridview += "<tr><td>" + data[i].AccountID +
"</td><td>" + data[i].TypeID_FK +
"</td><td>" + data[i].FriendlyName +
"</td><td>" + data[i].Currency +
"</td><td>" + data[i].AvailableBalance + "</td></tr>";
}
gridview += "</table>";
$("#display2").html(gridview);
});
})
.fail(function(jqXHR, textStatus, errorThrown ){
alert(jqXHR.responseText + "An error has occurred during processing your request.");
});
};

Undefined object while populating dropdownlist using JSON in MVC2

i have some trouble while making two dropdownlist:
Area: All Areas
City: City that belong to the selected value of the Area
everything is fine till City read the items from JSON. All of the items in dropdown City are Undefined.
Here's my code
$(document).ready(function () {
$('#AreaList').change(function () {
$.ajaxSetup({ cache: false });
var selectedItem = $(this).val();
if (selectedItem == "" || selectedItem == 0) {
//Do nothing
} else {
$.ajax({
url: '<%=Url.Content("~/") %>Administration/GetDropDownCity',
data: { item: $("#AreaList> option:selected").attr("value") },
dataType: 'json',
traditional: true,
type: 'POST',
success: function (data) {
var items = "";
$.each(data, function (i, data) {
items += "<option value='" + data.value + "'>" + data.description + "</option>";
});
$("#CityList").html(items);
$("#CityList").removeAttr('disabled');
}
});
}
});
});
The Json does exist, I check on the Firebug and listed as below:
"[{\"value\":\"107\",\"description\":\"KOTA DEPOK\"},{\"value\":\"141\",\"description\":\"KOTA JAKARTA SELATAN\"}]"
any idea to solve this problem?
Edit
The problem is solved: I use jQuery.parseJSON() to read JSON.
I'm not sure but I think a variable is in conflict here
$.each(data, function (i, data) {
items += "<option value='" + data.value + "'>" + data.description + "</option>";
});
in enumerator change data to val for instance like
$.each(data, function (i, val) {
items += "<option value='" + val.value + "'>" + val.description + "</option>";
});
Edit: also try alerting data[0].value or data[0].description to make sure that json string is parsed correctly on client side, otherwise you may have to call $.parseJson on returned data.
Edit 2: one thing you can try is to use for loop
for(i=0;i<data.length;i++)
{
items += "<option value='" + data[i].value + "'>" + data[i].description + "</option>";
}

Categories