asp.net mvc4 jquery ui autocomplete not working - asp.net-mvc

I want to use autocomplete widget in asp.net mvc4 app. I was able to call the action to get list of autcompletition values from controller. Unfortunetely I am not able to add it to list of suggestions. I think that .map(data, function(item) in success part of autocomplete ajax call is not working. But I really do not know why. I am sure that all the scripts and css are load corectly. I am stating controller action returining suggestions list, also script in view and response from firebug. I was also trying the demo example from jqueryui page and it was working, but somehow it does not work over my returned data. Can someone help me and tell me why? Thank you in advance.
Action in Controller:
public ActionResult GetCities(int RegionId, string Name)
{
var ret = db.Cities.Where(c => c.RegionId == RegionId &&
c.Name.Contains(Name)).Select(a => new{ CityId = a.CityId, Name = a.Name});
return Json(ret);
}
Script in view:
<script type="text/javascript">
$(function() {
$("#City").autocomplete({
source: function(request, response) {
$.ajax({
url: "#Url.Action("GetCities")",
dataType: "json",
contentType: "application/json; charset=utf-8",
method: "POST",
data: "{'RegionId': " + $("#Region").val() + ", 'Name': '" + request.term + "'}",
success: function (data) {
response( $.map( data, function( item ) {
return {
label: item.Name,
value: item.Name
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
Response (from firebug)
[{"CityId":16,"Name":"Kordíky"},{"CityId":94,"Name":"Korytárky"}]

So I find out it was working, the only problem was, that I had breakpoint in visual studio and this breakpoint was supressing autocomplete suggestion list.

for Mvc Artitecture you must delete already imbended #Scripts.Render("~/bundles/Jquery") and #Scripts.Render("~/bundles/Jqueryval")
on all .cshtml files at the end and for also views/Shared/_layout.cshtml at the
end and put our jaquery suitable files on his suitables .cshtmls files in head...and lets enjoy.

Related

Search file in Folder MVC ASP.Net

I started working with MVC ASP.NET and i am stuck on 2 points.
How to search file in folder. For example if one file is inserted in folder then the system will pick this file and add display in list. (only newly inserted file).
Where should i add this code. Model or Control (not in view I guess).
Please help in this matter.
You will be writing your codes in the controller. You got negative points, because you didnt do anything on your own.
cheers
You can search a file in the View or in the Controller. In below I will explain how to do it in the controller with AJAX.
Add this to your View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function Check() {
$.ajax({
type: "POST",
url: '#Url.Action("SearchFile")',
data: '{fileName: ' + $('#input1').val() + '}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#result").val(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.status + " " + jqXHR.statusText);
}
});
}
</script>
<div>
<input id="input1">
<button id="btnCheck" onclick="Check()"> Check </button>
<span id="result"></span>
</div>
And I must Add a controller for getting the file name from AJAX and searching it.
[HttpPost]
public ActionResult SearchFile(string fileName)
{
if (!Request.IsAjaxRequest())
return Json(false);
var relativePath = "~/YourFolder/" + fileName;
var absolutePath = HttpContext.Server.MapPath(relativePath);
return Json(System.IO.File.Exists(absolutePath));
}

How to use ajax in mvc?

I am a very beginner to mvc and ajax both.
I have tried many examples on net but I don't understand how ajax is used practically?
I have a controller named members which has GetAllMembers Method.
GetAllMembers returns a List<Members>
Now I want to use JQuery and ajax something like :
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function () {
},
error: function () {
alert("Failed to get the members");
}
});
});
Is my URL right?
Upon success I want to display that List in a ListBox.
How can I get it? Can anyone give me a start?
$.ajax({
type: "POST",
url: "Members/GetAllMembers", //Your required php page
data: "id="+ data, //pass your required data here
success: function(response){ //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page.
},
error: function () {
alert("Failed to get the members");
}
});
Hope this will help you.. :)
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function (result) {
// do your code here
},
error: function () {
alert("Failed to get the members");
}
});
});
So your request give response in "result" variable. So you have to easily manage result variable value in foreach loop and set value in ListBox HTML.
Follow this example:
suppose you have this html:
<p>List Box - Single Select<br>
<select id="listBox" name="listbox">
</select>
</p>
So we have this js:
var template = '<option value="$value">$name</option>';
var getAllMembers = function() {
$.ajax({
url: 'Members/GetAllMembers',
dataType: 'json', //Assuming Members/GetAllMembers returns a json
success: function(response) {
$.each(response, function(index){
var option = template.replace(/\$value/g, this.value)
.replace(/\$name/g, this.name);
$('#listBox').append(option);
});
}
});
};
EDIT: Now you only need to call getAllMembers(); function.
Hope this help.
Pablo.

jQueryMobile - looping each button to change text of nested tag on click with ajax

I have a page that will make an external call on a button click, and then update the button to reflect success. The ajax calls work properly, however I am having difficulty trying to manipulate the text of the button when there are many on the page.
It is easy enough to match using $(".sabPauRes.ui-btn-text").text("Updated"); when it's the only item on the page, but I am not sure how to point to it using $(this) when I am using the each function. I read a bit about 'closest', but it doesn't seem to accomplish what I want (or I'm just doing it wrong).
Code sample below!
$(document).ready(function(){
$('.sabPauRes').each(function() {
$(this).click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: this.href,
cache: false,
dataType: "text",
success: onSuccess
})
})
$("#resultLog").ajaxError(function(event, request, settings, exception) {
$("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
})
function onSuccess(data)
{
// validate the result of the ajax call, update text, change button methods as needed
if (data == "Success") {
// PROBLEM -- how do I use $this to match a class that is nested within it?
$(this).closest(".ui-btn-text").text("Updated");
} else {
alert("Failed: " + data);
}
$("#resultLog").html("Result: " + data);
}
})
})
html
<body>
<div data-role="page">
<div data-role="content">
<div data-role="collapsible">
<h3>This is an item</h3>
<p>
Resume Download
<div id="resultLog"></div>
</p>
</div>
</div>
</body>
Found the answer within Change button text jquery mobile
If you assign $(this) to a variable, then you can reference it in the .text() function as shown below:
$(document).ready(function(){
$('.sabPauRes').each(function() {
$this = $(this);
$(this).click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: this.href,
cache: false,
dataType: "text",
success: onSuccess
})
})
$("#resultLog").ajaxError(function(event, request, settings, exception) {
$("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
})
function onSuccess(data)
{
// validate the result of the ajax call, update text, change button methods as needed
if (data == "Success") {
alert(data);
$(".ui-btn-text",$this).text("Updated");
} else {
alert("Failed: " + data);
}
$("#resultLog").html("Result: " + data);
}
})
})
First things first. Please stop using jquery ready handler when working with jQuery Mobile. Give your page an id and use pageinit() event instead.
pageinit = DOM ready
One of the first things people learn in jQuery is to use the
$(document).ready() function for executing DOM-specific code as soon
as the DOM is ready (which often occurs long before the onload event).
However, in jQuery Mobile site and apps, pages are requested and
injected into the same DOM as the user navigates, so the DOM ready
event is not as useful, as it only executes for the first page. To
execute code whenever a new page is loaded and created in jQuery
Mobile, you can bind to the pageinit event.
You can save a ref to the clicked button and use it in success and error handlers like this:
$(document).on("pageinit", "#page1", function(){
$(document).on("click", "a.sabPauRes", function(event){
event.preventDefault();
//Save a ref to the clicked button
$this = $(this);
$.ajax({
type: "GET",
url: this.href,
cache: false,
dataType: "text",
success: function (data){
// validate the result of the ajax call, update text, change button methods as needed
if (data == "Success") {
$this.find(".ui-btn-text").text("Updated");
} else {
$this.find(".ui-btn-text").text("Failed");
}
$("#resultLog").html("Result: " + data);
},
error: function(jqXHR, textStatus, errorThrown) {
$this.find(".ui-btn-text").text("Error");
$("#resultLog").html("Error Calling: " + $this.attr("href") + "<br />HTTP Code: " + jqXHR.status + " " + jqXHR.statusText);
}
})
});
});
Here is jsFiddle

JQUERY GET operation not working

I'm having trouble with the following JQuery script
$('#extra_data').append('<div id="tabs-' + (tab_length + 1) + '"></div>');
$.get(url, function(data) {
$('#tabs-' + (tab_length + 1)).html(data);
});
My trouble is that the $.get(..) operation doesn't return any results - although when using firebug it shows the ajax call as expected.
Any clues?
Thanks.
Controller
<HttpPost()> _
Function GetPartialView() As ActionResult
If (Request.IsAjaxRequest()) Then
Return View("PVTest")
Else
Return View()
End If
End Function
I've filtered the request if it is Ajax. You can even pass an object to your partial view.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'Home/GetPartialView',
data: {},
dataType: 'json',
beforeSend: function(XMLHttpRequest) {
},
complete: function(XMLHttpRequest, textStatus) {
$('#extra_data').append(XMLHttpRequest.responseText);
}
});
});
</script>
Partial View (PVTest.ascx)
<%# Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl" %>
<div id="01">
Hello World
</div>
Try load method:
$('#extra_data').append('');
$('#tabs-' + (tab_length + 1)).load(url)
I think you need to use Post and [HttpPost] in ASP.NET MVC, I think there is a security
issue related to GET.
I only seem to use Post operations and remember seeing something about security.
Will see if I can verify that...
ADDED:
see: ASP.NET MVC 2.0 JsonRequestBehavior Global Setting
I would use a POST, as Mark suggested:
$.ajax({
type: 'POST',
url: url,
data: { },
dataType: 'json',
beforeSend: function(XMLHttpRequest) {
},
complete: function(XMLHttpRequest, textStatus) {
var Response = $.parseJSON(XMLHttpRequest.responseText);
}
});
the Response should contain the JSON stream. You can append it to your element.
The controller should do something like this:
<HttpPost()> _
Function DoSomething() As ActionResult
Return (Json(myObject, JsonRequestBehavior.DenyGet))
End Function

ASP.net MVC AutoComplete Erroring?

I'm trying to get an autocomplete field firing in my asp.net mvc website. Basically the user types in their location and i go out to my db and pre-populate with country and postcodes that match.
The problem im having is that when the view load an error throws saying "Microsoft JScript runtime error: Exception thrown and not caught". It is throwing in the jquery.Ui.widget.js file at the following line:
throw "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'";
Following is my script:
<script type="text/javascript" language="javascript">
$(function () {
$.ajaxSetup({ type: "POST" });
$('#Location').autocomplete('<%= Url.Action("Find") %>', {
dataType: 'json',
parse: function (data) {
var rows = new Array();
for (var i = 0; i < data.length; i++) {
rows[i] = { data: data[i], value: data[i].PlaceName, result: data[i].PlaceName, id: data[i].LocationID };
}
return rows;
},
formatItem: function (row) {
return row.PlaceName;
},
delay: 300,
autofill: true,
selectFirst: true,
highlight: false
}).result(function (event, row) {
$("input[id$='LocationID']").val(row.LocationID);
});
});
</script>
I've made sure all the needed jquery files are attached but still cant get it to fire. Ive got the simple default functionality of the autocomplete control to fire (showing a prepopulated list), but as soon as i try to pull from a Json datatype it gives me grief.
Any ideas?
You can check out my answer to Ben here, hopefully it will help you too.

Resources