I am binding dropdown list using jquery and asp.net callbacks.
this is working in IE-9,11 and other browsers also but It is not working in IE-8.
and It is not showing any error also.
I am using bellow javascript function for binding dropdown
function ClientCallback(result, context) {
if (!$('#ddltest')) {
return;
}
$('#ddltest').length = 0;
if (!result) {
return;
}
$(result).find('Table1').each(function () {
var OptionValue = $(this).find('OptionText').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$('#ddltest').append(option);
});
}
from code behind method I am returning dataset in the form of xml like return ds.GetXml();
Related
I am creating a cascading dropdown list based on an example I found here
The query sent to the server to request the second dropdownlist values has non null parameters but when I break in the controller method, it appears empty. As you can see below.
Any help would be greatly appreciated ! Thanks !!
It's using jQuery and ASP.NET MVC 5 while my project is ASP.NET MVC Core 2
The code in the controller is the following :
public JsonResult States(string Country)
{
List<string> StatesList = new List<string>();
switch (Country)
{
case "India":
StatesList.Add("New Delhi");
StatesList.Add("Mumbai");
StatesList.Add("Kolkata");
StatesList.Add("Chennai");
break;
}
return Json(StatesList);
}
And here is the AJAX :
<script src = "/lib/jquery/dist/jquery.js" > </script>
<script>
$(document).ready(function ()
{
$("#State").prop("disabled", true);
$("#Country").change(function ()
{
if ($("#Country").val() != "Select")
{
var CountryOptions = {};
CountryOptions.url = "/Dropdown/states";
CountryOptions.type = "POST";
CountryOptions.data = JSON.stringify({ Country: $("#Country").val() });
CountryOptions.datatype = "json";
CountryOptions.contentType = "application/json";
CountryOptions.success = function (StatesList)
{
$("#State").empty();
for (var i = 0; i < StatesList.length; i++)
{
$("#State").append("<option>" + StatesList[i] + "</option>");
}
$("#State").prop("disabled", false);
};
CountryOptions.error = function ()
{
alert("Error in Getting States!!");
};
$.ajax(CountryOptions);
}
else
{
$("#State").empty();
$("#State").prop("disabled", true);
}
});
});
Since you have specified the contentType = "application/json" and are sending stringified data, then you need to add the [FromBody] attribute in the POST method to instruct the ModelBinder to use the content-type header to determine the IInputFormatter to use for reading the request (which for json is the JsonInputFormatter). Change the signature of the method to
[HttpPost]
public JsonResult States([FromBody]string Country)
However, it is not necessary send the data as json, and you can use the default contentType ('application/x-www-form-urlencoded; charset=UTF-8'). You can delete the contentType option and use
CountryOptions.data = { Country: $("#Country").val() }; // not stringified
// CountryOptions.contentType = "application/json";
For more information, refer Model binding JSON POSTs in ASP.NET Core.
I'm using ChromiumWebBrowser to load a website, and after page loaded, I'll execute some script
browser.ExecuteScriptAsync(script)
But that website not use jquery, so difficult to code my script. I want to inject jquery into that site to write my script easier. How can I do it? Thank you very much
EDIT:
I have had a jquery file in my computer. And I would like to add it to the page where I want to crawl data. I tried using LoadingStateChanged event, but not worked.
private void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
lbStatus.SetText(e.IsLoading ? "Loading..." : browser.Address);
if (!e.IsLoading)
{
//Load jquery
}
else
{
}
}
Set this code to script variable as string and then call browser.ExecuteScriptAsync(script)
(function () {
// more or less stolen form jquery core and adapted by paul irish
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState
|| this.readyState == 'loaded'
|| this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
getScript('http://code.jquery.com/jquery-latest.min.js', function () {
if (typeof jQuery == 'undefined') {
console.log('Sorry, but jQuery wasn\'t able to load');
} else {
console.log('This page is now jQuerified with v' + $.fn.jquery);
$(document).ready(function () {
alert(1);
//here you can write your jquery code
});
}
});
})();
i push the entire jquery js-file as inline-code and works great:
browser.ExecuteScriptAsync(File.ReadAllText(#"content\jquery.1.11.1.min.js"));
reduces loading times...
it's very easy :)
string script_1 = "document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).src = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'";
browser.ExecuteScriptAsync(script_1);
and for call any custom jquery function or class:
string script_2 = "$('.contact').css('color','#aabbcc');";
browser.ExecuteScriptAsync(script_2);
I am using select2 library for replacing select boxes. I rearranged example 7 that you can find on Select2 library page (scroll down with id
$("#e7").select2 etc...). I made my own generic handler that return serialized json data:
GetData.asxh view :
public class GetData : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public class RecipesList
{
public int total { get; set; }
public List<TopRecipeTable> recipes { get; set; }
public RecipesList() { }
public RecipesList(int total, List<TopRecipeTable> recipes)
{
this.total = total;
this.recipes = recipes;
}
}
private string GenerateJsonSerializedObject(int languageId, string orderBy)
{
RecipesList recipeList = new RecipesList(15, DBDataBase.GetTopRecipesByNumberOfRecipes(languageId, 15));
return new JavaScriptSerializer().Serialize(recipeList);
}
public void ProcessRequest(HttpContext context)
{
int languageId;
bool languageParsed = int.TryParse(context.Request["languageId"], out languageId);
string orderBy = (string)context.Request["orderBy"];
if (languageParsed && orderBy != string.Empty)
{enter code here
context.Response.ContentType = "application/json";
var jsonValue = GenerateJsonSerializedObject(languageId, orderBy);
context.Response.Write(jsonValue);
}
}
This generic handler returns the right format of json (I checked it with this URL ). My result (json) is also the same as the one in example on above mentioned page. But after this jquery doesn`t fire anymore.
My script :
$(document).ready(function () {
$("#e8").select2({
placeholder: "Search for a recipe",
//minimumInputLength: 1,
ajax: {
url: "/Handlers/GetData.ashx",
dataType: 'jsonp',
data: function (term, page) {
return {
languageId: 1,
orderBy: "TA"
};
},
results: function (data, page) {
alert(data.total);
var more = (page * 10) < data.total; // whether or not there are more results available
// notice we return the value of more so Select2 knows if more results can be loaded
return { results: data.recipes, more: more };
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
});
I tried to write the same alert(data.total) in the original example and it worked but not in my version. So I have the right json format, the jquery calls my generic handler and also recieved parameters languageId ... and also return the right json format but than nothing. I don't know if I am missing something here, because I am sure that this thing could also work with a generic handler as well. I hope I gave enough information about my problem.
I can also add my result in jquery .ajax error handler :
xhr.status = 200
ajaxOptions = parsererror
horwnError = SyntaxError : invalid label
If this is any helpful information
This question is quite old, so pretty sure you have a solution by now...but:
Remove all of these functions:
formatResult: movieFormatResult
formatSelection: movieFormatSelection
dropdownCssClass: ...
escapeMarkup:....
You did not provide those functions to format your data did you? All of those are only needed if you are making a custom drop down of items.
You are returning data.recipes - that needs to be an array of {Text:"", Id:""} or you need to build it from what you return right there.
First, get it working with just a very basic list with very basic data...then go from there.
Additionally, when you get that working try using WebApi or ServiceStack to handle your data instead of an IHttpHandler.
I'm working through a SignalR demo that displays database info in a list when a button is hit.
My Hub has 2 functions: One to remove DB objects from a list, and one to re-add DB objects to that list.
These functions are performed in my View and perform great when I only have the page open once. But if I open the page in another tab (can be the same browser or a different one), the pages do not stay in sync.
Meaning, when one page's button is hit, the other page is not displaying the data correctly.
Often times one page will do fine, while the other will perform the remove but not the add! It's mind-boggling. They should just be reflections of each other from my understanding.
Has anyone else run into something similar?
Thanks in advance for any help!
Here's my Hub :
[HubName("hubtest")]
public class HubTest : Hub
{
CmsContext db = new CmsContext();
public void showdata()
{
var f = from x in db.Data
select x;
Clients.remove();
Clients.add(f);
}
}
And here's the javascript in my View for the functions:
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-0.5.2.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var hubtest = $.connection.hubtest;
hubtest.remove = function () {
//clear list of any prior values
var list = document.getElementById('dataList');
while (list.hasChildNodes()) {
list.removeChild(list.childNodes[0])
}
};
hubtest.add = function (data) {
//populate with updated values
for (var i = 0; i < data.length; i++) {
var element = data[i];
$('#dataList').append('<li>' + element.Question + '</li>');
}
};
$("#broadcast").click(function () {
hubtest.showdata();
});
// Start the connection
$.connection.hub.start();
});
</script>
<input type="button" id="broadcast" value="broadcast" />
<ul id="dataList">
</ul>
Try this instead:
<script type="text/javascript">
$(function () {
var hubtest = $.connection.hubtest;
hubtest.add = function (data) {
//clear the values first.
var list = $('#dataList');
list.empty();
//populate with new values
for (var i = 0; i < data.length; i++) {
var element = data[i];
list.append('<li>' + element.Question + '</li>');
}
};
$("#broadcast").click(function () {
hubtest.showdata();
});
// Start the connection
$.connection.hub.start();
});
</script>
And this:
[HubName("hubtest")]
public class HubTest : Hub
{
TestDatabaseEntities db = new TestDatabaseEntities();
public void showdata()
{
var f = from x in db.FAQs
select x;
Clients.add(f);
}
}
First of all thanks for your replies. I really appreciate your feedback!
I eventually got it to where my pages are staying in sync when open in multiple tabs by altering how my data is sent to the View.
Where I was performing the for loop in my Javascript to display each piece of data, now I am doing that in my Hub like so:
[HubName("hubtest")]
public class HubTest : Hub
{
CmsContext db = new CmsContext();
public void showdata()
{
Clients.clearlist();
var faqs = from x in db.Faqs
select x;
foreach (Faq faq in faqs)
{
Clients.add(faq.Question.ToString());
}
}
}
Then my Javascript is just appending that FAQ question to the list:
$(function () {
var hubtest = $.connection.hubtest;
hubtest.clearlist = function () {
var list = $('#datalist');
list.empty();
};
hubtest.add = function (data) {
$('#datalist').append('<li>' + data + '</li>');
};
$("#broadcast").click(function () {
hubtest.showdata();
});
// Start the connection
$.connection.hub.start();
});
Sending just a simple string of my data to be printed individually seems to allow my page to stay in sync.
Before the data I was sending was a list of DB objects and my Javascript was looping through each and adding that object's Question column to the list. Not sure why this was such an issue - especially since it would work on one open tab but not all open tabs - but that simple change fixed my site sync issues.
Thanks again!
I am trying to use the jQuery Autocomplete UI widget on a text box and I am having no luck getting the source to work. I have a database full of names that I want the autocomplete to work against, so I created a page called searchpreload.aspx and it looks for a variable in the url and queries the db based on the querystring vraiable.
When I type in the search box, I am using the keyup function so I can capture what the value is that needs to be sent over. Then I do my string gathering from the db:
if (Request.QueryString["val"] != null)
{
curVal = Request.QueryString["val"].ToString();
curVal = curVal.ToLower();
if (Request.QueryString["Type"] != null)
type = Request.QueryString["Type"].ToString();
SwitchType(type,curVal);
}
It queries the database correctly and then it takes the strings and puts them in a list and prints them out to the page:
private void PreLoadStrings(List<string> PreLoadValues, string curVal)
{
StringBuilder sb = new StringBuilder();
if (PreLoadValues.Any())
{
foreach (string str in PreLoadValues)
{
if (!string.IsNullOrEmpty(str))
{
if (str.ToLower().Contains(curVal))
sb.Append(str).Append("\n");
}
}
Response.Write(sb.ToString());
}
}
This works fine, if I navigate to this page I get a listing of all of the data that I need, however I can not get it to show up in the autocomplete box. When I debug the code, the source of the autocomplete is calling this page correctly each time and getting the correct data, it just is not displaying anything. Am I doing something wrong?
JQuery Code:
<script type="text/javascript">
$(document).ready(function () {
$(".searchBox").focus();
var checked = 'rbCNumber';
$("input:radio").change(function (eventObject) {
checked = $(this).val();
});
$(".searchBox").keyup(function () {
var searchValue = $(".searchBox").val();
//alert("Searchpreload.aspx?val=" + searchValue + "&Type=" + checked);
$(".searchBox").autocomplete({
source:"Searchpreload.aspx?val=" + searchValue + "&Type=" + checked,
minLength: 2
});
});
});
</script>
Also, should I be doing this a different way to make it faster?
You arent displaying the results into anything - source will return a data item that you can then use to populate something else on the page. Look at autocomplete's select and focus methods.
here is an example of how i have done it:
field.autocomplete({
minLength: 1,
source: "whatever",
focus: function (event, ui) {
field.val(ui.item.Id);
return false;
},
search: function (event, ui) {
addBtn.hide();
},
select: function (event, ui) {
setup(ui);
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.Id+ ", " + item.Name + "</a>")
.appendTo(ul);
};
The .data part is the part you are missing. Once the data comes back from the autocomplete you arent doing anything with it.
The source does not need to include the term the user entered into the search box. Jquery will automatically append the term onto the query string for you. If you watch the request get generated in firebug, you will see the term query hanging off the end of the url.