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

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>' +

Related

Not getting a list of table in ajax array

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>

Get clicked image id on dynamic div

In here I am able to display university images on dynamically created div. Now I want to get id of the university image which user selected, then use that id to display courses which selected university offer. Is there way to do that?
protected void fetchUniversities()
{
List<University> uniList = new List<University>();
using (var dd = new UniversityContext())
{
uniList = UniversityController.fetchUniversitiesOfferCourses(dd);
}
Literal header = new Literal();
header.Text = "<div class=\"container\"><div class=\"row\"><h2>Apply For University</h2><p>Select your preferred university</p></div></div>";
CompanyPanel.Controls.Add(header);
foreach (var item in uniList)
{
Literal label1 = new Literal();
label1.Text = "<div class=\"container\"><div class=\"row\" >";
Literal lblTwo = new Literal();
lable2.Text = "<img src=\"/template/images/" + item.ImageName + "\" height=\"100%\"/>";
Literal lblLast = new Literal();
label3.Text = "</div></div>";
Panel1.Controls.Add(label1);
Panel1.Controls.Add(label2);
Panel1.Controls.Add(label3);
}
}
You could achieve this in a better way by moving to a different framework and return data (e.g. JSON) in response to an ajax query (have a look at ASP.NET MVC).
Here is a way to achieve this using your example, it's a bit cumbersome and I haven't tested it but should get you in the right direction
Add a method as follows:
[WebMethod]
public static string GetUniversityCourses(int universityId)
{
List<UniversityCourses> courses = ...
StringBuilder coursesHtml = new StringBuilder();
foreach(var course in courses) {
//Generate your html here
coursesHtml.Append("<div>" + course.Name + "</div>";
}
return coursesHtml.toString();
}
Then add this javascript code to you aspx file:
function GetUniversityCourses(id) {
$.ajax({
type: "POST",
url: "Default.aspx/GetUniversityCourses",
data: {"id": id,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
complete: function (jqXHR, status) {
$("#coursesContainer_" + id).html(jqXHR.responseText);
}
});
}
Then in your server side code:
lable2.Text = "<img src=\"/template/images/" + item.ImageName + "\" height=\"100%\"/><div id=\"coursesContainer_\"" + item.Id + "</div><script>$('a[data-getcourseid=\"" + item.Id + "\"]').on('click', function() { GetUniversityCourses(" + item.Id + ")}</script>";

jQuery Select2 ajax data source not triggered / called

I'm trying to bind my Select2 dropdown list to an MVC (v5.2.3) controller of my application.
I've pretty much copied the code from the demo:
<select id="select-ticket-test" class="duplicate-post-select" style="width: 100%;" placeholder="Select ticket">
<option></option>
<option value="3620194" selected="selected">select2/select2</option>
</select>
#section Scripts {
<script type="text/javascript">
function formatTicket(ticket) {
if (ticket.loading) {
return ticket.text;
}
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__avatar'><img src='" + ticket.owner.avatar_url + "' /></div>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + ticket.full_name + "</div>";
if (ticket.description) {
markup += "<div class='select2-result-repository__description'>" + ticket.description + "</div>";
}
markup += "<div class='select2-result-repository__statistics'>" +
"<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + ticket.forks_count + " Forks</div>" +
"<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + ticket.stargazers_count + " Stars</div>" +
"<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + ticket.watchers_count + " Watchers</div>" +
"</div>" +
"</div></div>";
return markup;
}
function formatTicketSelection(ticket) {
return ticket.Id || ticket.Subject;
}
$("#select-ticket-test").select2({
placeholder: "Select a state",
allowClear: true,
ajax: {
url: "#Url.Action("GetAjaxAsync")",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term,
pageSize: params.page,
pageNum: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: false
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatTicket,
templateSelection: formatTicketSelection
});
</script>
}
public async Task<ActionResult> GetAjaxAsync(string searchTerm, int pageSize, int pageNum)
{
long number = Convert.ToInt64(searchTerm.Replace("T", null));
var posts = await UnitOfWork.SupportPosts.Where(x => x.Number == number).ToListAsync();
var json = new
{
Results = posts.Select(x => new
{
x.Id,
x.NumberName
}),
Total = posts.Count
};
return Json(json, JsonRequestBehavior.AllowGet);
}
What I've noticed is, that the placeholder isn't even shown. The Select2 is initialized (as in "not a "real" dropdown anymore"), but no placeholder is shown. And when typing into the textbox, no call is even made to my controller.
There are no JavaScript errors in the console either.

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){

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.");
});
};

Categories