I'm going to use owl carosel.In the hardcoded div's working.Now i want to get this type via ajax function.I'll try to do this in several ways but not success.
My Webmethod it returns the Image Path & Caption values.
<div id="owl-demo">
<div class="item"><a class="item link"><img src="/Content/images/sdfdfd.png" alt="Owl Image"></a><p><center>CAPTION</center></p></div>
<div class="item"><a class="item link"><img src="/Content/images/tyty.png" alt="Owl Image"></a><p><center>CAPTION</center></p></div>
</div>
My Ajax function(instead of that hardcoded values )
function GetAllImages()
{
$.ajax({
type: "POST",
url: "/Dest/GetAllImages",
success: function (msg) {
debugger;
if (msg._allImg.length > 0) {
$.each(msg._allImg, function (index, item) {
//In here i need to construct that above pattern
//My Webmethod it returns the Image Path & Caption values.
var html = $("<div>").html();
var html2 = $("<img src").html();
$('#owl-demo').append(html);
});
}
else {
}
}
});
}
If I follow you, I think you mean:
$('#owl-demo').append('<div class="item"><a class="item link"><img src="/Content/images/' +
item.url + '" alt="Owl Image"></a><p><center>' +
item.caption + '</center></p></div>');
Related
Using jQuery, I am dynamically adding a group of <ul> elements to a <div> using .append. I loop through a table containing a value for each <ul> I want added. That part works fine. Where I am having an issue is trying to add Razor functionality to the <li> elements.
Although the end result HTML produced looks to be syntax correct HTML, the Razor code does not function.
End Result HTML:
<div id="div_1">
<label>Clients</label>
<ul>
#if (Model.details != null)
{
foreach (var itm in Model.details.OrderBy(i => i.value))
{
<li>#itm.value</li>}
}
</ul>
</div>
The HTML above is what is produced by my .append code. It can be hard coded into my cshtml page and works perfectly. Adding it via .append at run time does not which I assume revolves around creation time or sequence?
Scaled down version of my code below:
Controller:
[HttpGet]
public JsonResult ClientMap()
{
var db = new EDM_Client();
List<client_map> map = new List<client_map>();
map = db.client_map.ToList();
return Json(map, JsonRequestBehavior.AllowGet);
}
csHTML:
<div id="divDetails" class="row">
</div>
jQuery:
//getClientMap temporarily called from a button click
getClientMap(function (map) {
$.each(map, function (idx, obj) {
$('#divDetails').append('<div id="div_' + obj.detail_id + '">' +
'<label>' + obj.detail_hdr + '</label>' +
'<ul>' +
'#if (Model.details != null)' +
'{' +
'foreach (var itm in Model.details.OrderBy(i => i.value))' +
'{' +
'<li>' +
'#itm.value' +
'</li>' +
'}' +
'}' +
'</ul>' +
'</div>');
});
});
function getClientMap(output) {
$.ajax({
url: './Client/ClientMap',
type: "GET",
dataType: "json",
async: false,
success: function (data) {
output(data);
}
});
I am trying to do this dynamically so <ul> can be easily added/deleted via table entries rather than coding changes.
Any advice on how to make this work (or an alternative way) is appreciated.
jQuery runs on the client's machine, so when you use it to generate Razor code, the client machine cannot run that code because it has to run on the server.
You can put the Razor code directly where it should be, and then use jQuery to show/hide the options as required.
Alternatively, change your Ajax method ClientMap to return a partial view instead of JSON string, then use the jQuery's html() function to add the HTML returned from Ajax:
$('#divDetails').html(data);
I have a HTML dropdown list for countries. Now I want to populate the City dropdown accordingly using ajax
<select class="form-control" id="ddCountry" runat="server" tabindex="8"></select>
<select class="form-control" id="ddCity" runat="server" tabindex="9"></select>
<script type="text/javascript">
$('#ddCountry').on('change', function () {
var storeData = { countryId: this.value }
$.ajax({
type: "POST",
url: "UserRegistration.aspx/GetCities",
data: JSON.stringify(storeData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("The data in list is "+data);
},
error: error
});
});
</script>
My method on .cs page is as follows:
[WebMethod]
public static List<CityBO> GetCities(string countryId)
{
//returning cities
}
The problem is I am able to fetch the data in GetCities method but not able to show it in the ddCity list because it is a HTML control and the method is static, so
ddCity.Items.AddRange(list_of_countries) is not working as ddCity is not being recognized in static method. Please tell how to fill the dropdown list.
You cannot access controls in static method. You need to return list of cities from webmethod and fill dropdown using javascript.In success method of ajax write code like this.
success: function (data) {
fillDropDown(data.d);
}
function fillDropDown(data){
var html = "";
for (var i = 0; i < data.length; i++)
{
html += "<option value='" + data[i].ValueField+ "'>" +
data[i].TextField+ "</option>";
}
$("select[id$=ddlCity]").html(html);
}
You can use ajax success function given below.
success: function (data)
{
var lankanListArray = JSON.parse(data.d);
// running a loop
$.each(lankanListArray, function (index, value)
{
$("#ddlCity").append($("<option></option>").val(this.name).html(this.value));
});
}
I have a javascript function and c# fanction. I need to call to the c# function from the javascript function, but I don't know how...
Can someone help me?
Thank you!
The javascript function-
<script type="text/javascript" language="javascript">
function DeleteBook(idimg) {
// idimg is a string
var userConfirm = window.confirm('Are you sure?');
if (userConfirm == true) {
control.Sess(idimg);// The line which is colling to the c# function - doesn't work
window.open('Delete.aspx');
}
else
return false;
}
</script>
The c# function-
protected void Sess(string id)
{
Session["forDelete"] = id;
}
You can create a web method
[WebMethod(EnableSession = true)]
public static Application GetApplication(int id)
{
}
and in javascript you then do something like this
$.ajax(
{
type: "POST",
url: "Applications.aspx/GetApplication",
contentType: "application/json; charset=utf-8",
data: "{'id':" + id + "}",
dataType: "json",
success: methodToDoSomethingOnSuccess,
error: function (rhq, textStatus, errorThrown) {
alert ("some went awry");
}
});
you have to create an input of type submit that invokes your C# function using the HTML and make it hidden. Then create a div tag and using javascript do this:
#CSS
.Hidden {
display:none;
}
#HTML
<input type="submit" id="SubmitTag" OnClick="C# Functin" class="Hidden" runat="server" />
//if using MVC and Razor
#using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post)) {
<input type="submit" id="SubmitTag" class="Hidden" />
}
<div id="OnDivClick"> what you want to do in here </div>
#JS
$('#OnDivClick').click(function () {
$('#SubmitTag').trigger("click");
});
Well, there are ways to do this but I believe that you're trying to save something in the Session for the Delete.aspx page to read it. The simplest solution is just post the data in:
var form = document.createElement("form");
form.setAttribute('method', 'post');
form.setAttribute('action', 'Delete.aspx');
form.setAttribute('target', '_blank');
form.innerHTML = '<input type="hidden" name="forDelete" value="' + idimg + '" />';
document.body.appendChild(form);
form.submit();
This dynamically creates a form and submits it with idimg which will open the page Delete.aspx in a new window.
All that's left to do is go to the C# part of Delete.aspx page and catch the incoming data:
string idimg = Request.Form["forDelete"];
// Do whatever with it
Session["forDelete"] = idimg; // If you still want to save it in Session
I am using following JQuery code from somewhere on the internet to load content on browser window scroll.
var pageIndex = 1;
var pageCount;
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords();
}
});
function GetRecords() {
pageIndex++;
if (pageIndex == 2 || pageIndex <= pageCount) {
$("#loader").show();
$.ajax({
type: "POST",
url: "CS.aspx/GetCustomers",
data: '{pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var customers = xml.find("Customers");
customers.each(function () {
var customer = $(this);
var table = $("#dvCustomers table").eq(0).clone(true);
$(".name", table).html(customer.find("ContactName").text());
$(".city", table).html(customer.find("City").text());
$(".postal", table).html(customer.find("PostalCode").text());
$(".country", table).html(customer.find("Country").text());
$(".phone", table).html(customer.find("Phone").text());
$(".fax", table).html(customer.find("Fax").text());
$("#dvCustomers").append(table).append("<br />");
});
$("#loader").hide();
}
As you can see its adding HTML table on response success. But I have an asp.net user-control that I want to add instead of this HTML table when content scrolls (In short I want to add a server side control from JQuery). I can't add user-control's HTML in place of this HTML table because its code is too lengthy and complex and I don't know much JQuery. I am the beginner of the beginner concept of JQuery. Moreover I am a specialist in back-end programming. So, I can't code that business logic in JQuery. So any one please help me in doing so.
Like kintaro alerady suggested; render you html on server side (in a user control) and then load that control inside web method to return results in HTML to client side.
Here'a an example:
JavaScript code:
var pageIndex = 0;
var data = { "pageIndex": pageIndex };
$.ajax({
type: "POST",
url: "CS.aspx/GetCustomers",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8"
}).done(function (result) {
$("#dvCustomers").append(result.d);
});
and the PageMethod on server side:
[WebMethod]
public static string GetCustomers(int pageIndex)
{
Page pageHolder = new Page();
UserControl viewControl = (UserControl)pageHolder.LoadControl("_path_to_customers_usercontrol");
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
return output.ToString();
}
You will also have to pass a pageIndex value to Customers user controls, you can to that by casting the result of LoadControl method to a class that represnts your customer user control and then set PageIndex property.
If you are developing your project as ASP.NET Web Site you'll have to use reflection to set property value. Here's an example:
Type viewControlType = viewControl.GetType();
PropertyInfo field = viewControlType.GetProperty("PageIndex");
if (field != null)
{
field.SetValue(viewControl, pageIndex, null);
}
You can switch the HTML of the control with url parameter:
$.ajax({
type: "POST",
url: "CS.aspx/GetCustomers",
data: '{pageIndex: ' + pageIndex + ', ajaxcall: true}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
$("#dvCustomers table").append(data);
});
And in the ascx control:
<%if (Page.Request.QueryString.Get("ajaxcall") == "true")
{%>
normal html control render.
<%}
else
{%>
<tr>
<td>All data of table only tr an tds</td>
</tr>
<%} %>
Create a div and put your user control in this div. then set the visibility:hidden and once it is success display it(set visibility to visible using jquery) :
<div style="visibility:hidden" id="dv1">
<uc1:usercontrol Visible="true" runat="server">...
</div>
Jquery :
$("#dv1").css("visibility","visible");
I'm having a problem trying to get a ViewBage property value and pass it into a jQuery method.
For example, in my code below, #ViewBag.CountResult have the value 1, and it is displayed in my browser, but when passed into the updateResultFooter method, it is like "" ! Don't get why. Down is my view. Any help ?
Thanks in advance
<div>
<div>
<span>Téléphone ?</span>
<input id="idTxTel" type="text" name="txTelephone"/>
<input id="idBnSearch" type="submit" value="Chercher" name="bnSearch"/>
</div>
#Html.Partial("_Result", Model)
</div>
<script type="text/javascript">
var methodUrl = '#Url.Content("~/Search/GetReverseResult/")';
$(document).ready(function (){
updateResultFooter("#ViewBag.CountResult", "#ViewBag.PageNumber", "#ViewBag.PageCount");
$("#idBnSearch").click(function (){
var telValue = $("#idTxTel").val();
pageIndex = 0;
doReverseSearch(telValue, pageIndex, methodUrl);
updateResultFooter("#ViewBag.CountResult", 0, "#ViewBag.PageCount");
});
$("#bnNextPage").live("click", function (){
var telValue = $("#idTxTel").val();
pageIndex = pageIndex + 1;
doReverseSearch(telValue, pageIndex, methodUrl);
updateResultFooter("#ViewBag.CountResult", pageIndex, "#ViewBag.PageCount");
});
});
function updateResultFooter(resultCount, pageIndex, pageCount){
if (resultCount == '0')
$("#resultFooter").hide();
else
{
$("#resultFooter").show();
if (pageIndex == 0)
$("bnPreviousPage").attr('disabled', 'disabled');
else
$("bnPreviousPage").removeAttr('disabled');
if ((pageIndex + 1) == pageCount)
$("bnNextPage").attr('disabled', 'disabled');
else
$("bnNextPage").removeAttr('disabled');
}
}
function doReverseSearch(telValue, pageIdx, methodUrl){
$.ajax({
url: methodUrl,
type: 'post',
data: JSON.stringify({ Telephone: telValue, pageIndex: pageIdx }),
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#result').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
}
</script>
PS: I'm using this code to modify the display of the web page, depending on the result of a search made by the user.
I've changed the approach I was using. Now, I've changed my model so it contains the data I want to display, like (CountResult, PageCount). And it works fine now.