im trying to get a sech bar going for searching though a table and only displaying the results based off the title . the program does give me any errors or exceptions but when i press the search button nothing happens.
any help would be appreciated
the code inside my view
<script>
$(document).ready(function () {
getFileSharingsAjax(0)
});
function searchFileSharings() {
var searchQuery = $("#txtSearch").val();
getFileSharingsAjax(searchQuery);
}
function filterMovies() {
$("#txtSearch").val("");
getFileSharingsAjax("");
}
function getFileSharingsAjax(searchQuery) {
$.ajax({
type: "GET",
url:"#Url.Action("GetFileSharingsAjax")",
data: {
searchQuery: searchQuery
}, success:function(ViewResult){
$("#ajax-files").html(ViewResult);
}
});
}
</script>
my controller class
public ActionResult GetFileSharingsAjax(string searchQuery)
{
var query = from m in db.FileShare
select m;
if (!string.IsNullOrEmpty(searchQuery))
{
query = query.Where(s => s.Title.Contains(searchQuery));
}
return View("Files", query.ToList());
}
any help would be appreciated
Related
When I make ajax request to the server with breakpoint in the action method it stops on this breakpoint only the first time. After clicking for second, third etc. it goes but never stops on this breakpoint. When I change the method from GET to POST it stops every time. What is the reason for this behaviour ?
CLIENT SIDE:
$(function () {
setListAction();
});
function setListAction() {
$("li.list").on("click", function () {
alert("active");
var id = $(this).attr("file-id");
$.ajax({
type: "GET",
url: "TechAcc/ManageFile/" + id,
beforeSend: function myfunction() {
$("#loading").css("display", "block");
$("#fade").css("display", "block");
},
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}
});
});
}
SERVER SIDE:
[HttpGet]
public ActionResult ManageFile(int id = 0)
{
FileModel model = null;
if (id != 0)
model = new FileModel() { File = _repository.GetFileBy(id), GetAllFiles = _repository.GetAllFiles() };
else if (Session["Model"] != null)
model = (FileModel)Session["Model"];
else
model = new FileModel() { GetAllFiles = _repository.GetAllFiles() };
return View(model);
}
if your div with id "content" has list, it will not work.
<div id="content">
if your list is here, it won't work.
...
<li class="list">...</li>
...
</div>
if your design is like that, you need to bind click event after you replace your HTML response. i.e.,
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
//adding code here.
$("div#content").find("li.list").on("click", function() {
//same above click code should come here.
//Note: this newly added code block should not come here in click.
});
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}
Using the following script:
$(document).ready(function () {
$('#submit').click(function () {
var companyId = $('#companyCoid').val();
var erpKey = $('#erpKey').val();
if (companyId == "" || erpKey == "") {
alert("You have not entered enough information");
} else {
$.ajax({
type:post,
url: '#Url.Action("ErpDocument")',
data: {
coid: companyId,
documentKey: erpKey
}
});
}
});
});
I am trying to trigger this action result which would navigate to a new view:
[HttpPost]
public ActionResult ErpDocument(string coid, string documentKey)
{
var cview = new ConnectorViewModel();
Stuff and things here....
return View(cview);
}
I am getting the information from a form above and the check for blank fields works just fine, however, the function in my controller is never hit.
EDIT: Reason it wasn't hitting the ActionResult was I had post and not "POST", this now hits my method but does not display my new view.
I think the default contenttype is xml. you may need to add this
contenttype: "application/json; charset=utf-8"
. I think that's what I've had to do before. Although unlikely, you may need to add a datatype as well.
https://api.jquery.com/jQuery.ajax/
I am trying to build an autocomplete, but I have troubles patching along the parts.
First, my view include this field:
<p>#Html.TextBoxFor(_item => _item.mCardName, Model.mCardName, new { #class = "cardText", id = "card_name"} ) </p>
Very simple. Next, the javascript call:
<script type="text/javascript">
$(function() {
$('#card_name').autocomplete({
minlength: 5,
source: "#Url.Action("ListNames", "Card")",
select: function (event, ui) {
$('#card_name').text(ui.item.value);
},
});
});
</script>
Which calls this method:
public ActionResult ListNames(string _term)
{
using (BlueBerry_MTGEntities db = new BlueBerry_MTGEntities())
{
db.Database.Connection.Open();
var results = (from c in db.CARD
where c.CARD_NAME.ToLower().StartsWith(_term.ToLower())
select new {c.CARD_NAME}).Distinct().ToList();
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
If i insert the "Power" word, the JSON data is posted back like this:
{"ContentEncoding":null,"ContentType":null,"Data":[{"CARD_NAME":"Power Armor"},{"CARD_NAME":"Power Armor (Foil)"},{"CARD_NAME":"Power Artifact"},{"CARD_NAME":"Power Conduit"},{"CARD_NAME":"Power Conduit (Foil)"},{"CARD_NAME":"Power Leak"},{"CARD_NAME":"Power Matrix"},{"CARD_NAME":"Power Matrix (Foil)"},{"CARD_NAME":"Power of Fire"},{"CARD_NAME":"Power of Fire (Foil)"},{"CARD_NAME":"Power Sink"},{"CARD_NAME":"Power Sink (Foil)"},{"CARD_NAME":"Power Surge"},{"CARD_NAME":"Power Taint"},{"CARD_NAME":"Powerleech"},{"CARD_NAME":"Powerstone Minefield"},{"CARD_NAME":"Powerstone Minefield (Foil)"}],"JsonRequestBehavior":0,"MaxJsonLength":null,"RecursionLimit":null}
For reference purpose, here are two of the scripts that run:
<script src="/Scripts/jquery-2.0.3.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
However nothing is displayed. I would have liked to see the results displayed like a normal autocomplete would do. Can anyone help me out making things work?
EDIT
I have been working on this for a while. I have posted up there the new javascript, controller method and results obtained. But the thing still does not work and I would appreciate any help.
for autocompletes, i use the javascriptserializer class. the code goes something like this.
My.Response.ContentType = "application/json"
Dim serializer As JavaScriptSerializer = New JavaScriptSerializer
Dim dt As DataTable = GetDataTable("proc_name", My.Request.QueryString("term"))
Dim orgArray As ArrayList = New ArrayList
For Each row As DataRow In dt.Rows
Dim thisorg As New thisOrg
thisorg.id = row("organization_child_id")
thisorg.value = row("organization_name")
orgArray.Add(thisorg)
Next
My.Response.Write(serializer.Serialize(orgArray))
Public Class thisOrg
Public id As Integer
Public value As String
End Class
basically just takes a datatable, adds a series of objects to the array, then serializes it.
Finally! After taking a break, I got my answer.
See this?
public ActionResult ListNames(string _term)
{
using (BlueBerry_MTGEntities db = new BlueBerry_MTGEntities())
{
db.Database.Connection.Open();
var results = (from c in db.CARD
where c.CARD_NAME.ToLower().StartsWith(_term.ToLower())
select new {c.CARD_NAME}).Distinct().ToList();
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
As it happens, I was building a Json object OF another Json object. So that's why the data was not passed properly.
I've rebuilt the method, made it work, and refined it like this:
public JsonResult ListCardNames(string term)
{
using (BlueBerry_MagicEntities db = new BlueBerry_MagicEntities())
{
db.Database.Connection.Open();
var results = from cards in db.V_ITEM_LISTING
where cards.CARD_NAME.ToLower().StartsWith(term.ToLower())
select cards.CARD_NAME + " - " + cards.CARD_SET_NAME;
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return result;
}
And my javascript action:
<script type="text/javascript">
$(function() {
$('#searchBox').autocomplete({
source: function(request, response) {
$.ajax({
url: "#Url.Action("ListCardNames")",
type: "GET",
dataType: "json",
data: { term: request.term },
success: function(data) {
response($.map(data, function(item) {
return { label: item, value1: item };
}));
}
});
},
select:
function(event, ui) {
$('#searchBox').val(ui.item);
$('#cardNameValue').val(ui.item);
return false;
},
minLength: 4
});
});
</script>
And now everything works like a charm.
I am newbie to asp.net MVC4.
For searching names from list i tried a search filter in MVC4.
This is controller-
public ActionResult SearchUser(string Email, int? UserId) {
var system = from u in db.SystemUsers
select u;
if (!String.IsNullOrEmpty(Email)) {
system = system.Where(c => c.Email.Contains(Email));
}
return View(system.Where(x=>x.Email==Email));
}
View-
<input type="text" id="search-User" />
<button id="text-email">search</button>
Ajax handling-
<script type="text/javascript">
$(document).ready(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
alert(areavalue);
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json'
});
});
});
</script>
ViewModel-
public class UserModel
{
[Required]
public string Email { get; set; }
public int UserId { get; set; }
}
I have many users as a list, so i wanted to filter out any user from the list. For this I am using input element to get exact name as it is in list. Thus this name is passed to controller to find the exact match.
It is showing value i passed through ajax handling but not showing filtered result.
How can I perform searching in Asp.net MVC4?
I would use better Load() function for this porpose:
<script>
$(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
$(".YourDivForResults").Load('/Allusers/SearchUser/?Email=' + areavalue)
});
});
</script>
And, as a recommendation, modify a bit your ActionResult as follows:
system = system.Where(c => c.Email.ToUpper().Trim().Contains(Email.ToUpper().Trim()));
This way you will avoid problems with empty spaces and Upper or Low letters.
Your ajax function is sending the data up to the server, but it is not doing anything with the result. In order to use the results, you should use the done promise method in the jQuery .ajax method that you are calling. It will look something like this:
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json'
}).done(
function(data, textStatus, jqXHR) {
var object = jQuery.parseJSON(data);
// LOGIC FOR UPDATING UI WITH RESULTS GOES HERE
}
);
You could alternatively use the Success callback option (instead of done). But the key is to provide logic for what to do with the data returned by the Action.
Also, if you are intending to return results using your ViewModel, you may need to return UserModel objects from your Linq query.
And if you are expecting JSON back from your action, you should not return View. Instead, try returnins JSON(data). (See here for more).
You need to make small change to you action like,
public ActionResult SearchUser(string Email, int? UserId) {
var system = from u in db.SystemUsers
select u;
if (!String.IsNullOrEmpty(Email)) {
system = system.Where(c => c.Email.Contains(Email));
}
return Json(system.Where(x=>x.Email==Email),JsonRequestBehavior.AllowGet);
}
and in your ajax call
$(document).ready(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
alert(areavalue);
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json',
success:function(data){JSON.stringify(data);}
});
});
});
so that you will get the search result in a json format. you can make use of it. Hope it helps
$(document).ready(function ()
{
$(".viewmap").click(function ()
{
var id = $(this).attr("id");
var responseURL = "~/changemap?id=" + id;
//alert(responseURL);
$.ajax(
{
url: responseURL,
dataType: "json",
type:"GET",
success: function (dt)
{
initialize(dt.Latt, dt.Longt);
}
}
);
}
);
});
I use that script to make an ajax call to the page changemap.cshtml which does the following
#{
if(!IsPost)
{
if(!Request.QueryString["id"].IsEmpty()&&Request.QueryString["id"].IsInt())
{
var countryId=Request.QueryString["id"];
var db=Database.Open("GoogleMapView");
var dbCmd="SELECT * FROM places WHERE id=#0";
var row=db.QuerySingle(dbCmd,countryId);
if(null!=row)
{
Json.Write(row,Response.Output);
}
}
}
}
That is to return the queried data from the database in json format to the client. The Initialize function is defined as
function initialize(lat,lng)
{
var mapOptions = {
center: new google.maps.LatLng(lat,lng),zoom: 8,mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("gmap"),mapOptions);
}
But when I click the div tag of class viewmap, nothing happens. I think I miss some more script to get my application to work correctly.
I only try to implement a simple google map view in which once the user clicks a place name as a hyperlink will reload the map that matches with it.
I think
var responseURL = "~/changemap?id=" + id;
should be
var responseURL = '#(Url.Content("~/changemap")+"?id=")' + id;
try thr following
success(data){
initialize(data.d.Latt, data.d.Longt);
}
for more reference as in why d is used check the following link
http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/