do I need getJson at all? - c#

$(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/

Related

getting a search bar working using AJAX in ASP.net application

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

AJAX HTTP Method GET Goes To Server Only Once

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

How to get the Json Value correctly?

I am having a HttpPost request sending back an object Value.
I would like to make the ComputerLocation div appear when the object Value is true(s.IsComputer is a bool).
Currently nothing happens.
I tried to debug it using Firebug and verified that actually the request posts back the object Value:true, but when i check my result.Value, Value is shown as undefined.
Please check what I am doing wrong?
Script:
<script type='text/javascript'>
$(document).ready(function () {
$('#typeddl').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#typeddl').val() },
success: function (result) {
$('#ComputerLocation').toggle(result.Value === true);
}
});
});
$('#typeddl').trigger('change');
});
</script>
Json:
[HttpPost]
public JsonResult GetItemTypeForm(int itemTypeId)
{
//pseudo code
var data = from s in db.ItemTypes.ToList()
where s.ItemTypeId == itemTypeId
select new { Value = s.IsComputer };
return Json(data);
}
Use First method to get single result, because your query returns an IQueryable<T>
var data = (from s in db.ItemTypes.ToList()
where s.ItemTypeId == itemTypeId
select new { Value = s.IsComputer }).First();
Then return your result like this:
return Json( new { Value = data.Value });

Autocomplete: display results with json data

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.

Getting data from .aspx to jquery ajax

I'm novice in jquery and I have one problem:
I have two .aspx files: one of them contain script
<script type ="text/javascript">
$(document).ready(function () {
var schemaName = GetURLParameters('schemaName');
var key = GetURLParameters('key');
$.post("dataloader.aspx", {
name: schemaName,
key: key
});
});
</script>
which send parameters to other page, "dataloader.aspx". Here is "dataloader.aspx.cs" code:
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
var schemaName = Request.Form["name"];
var key = Request.Form["key"];
Loader loader = ConnectionManager.getLoader();
Dictionary<string, string> name_value = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(schemaName))
{
var schema = loader.GetSchema(schemaName);
var qcontext = new SimpleLoader.BOService.QueryContext();
qcontext.InitQueryContext();
var element = loader.GetObjectByKey(schema, key);
var viselems = element._Schema.GetVisibleElems();
var cardElems = viselems.Where(x => !(x is SchemaElemDetail)).ToList();
foreach (var elem in cardElems)
{
var value = (element.GetValue(elem.Name) ?? "").ToString();
if (!string.IsNullOrEmpty(value))
{
name_value.Add(elem.Name, value);
}
}
Response.Write(name_value);
Response.Flush();
Response.End();
}
}
As you can see, I,m adding some data to dictionary. I want to send this dictionary to "clientcard.aspx" client side by jQuery, but i don't know how...Can you help me?? I'll be very grateful.
A way would be to call a webmethod in dataloader.aspx. Assuming your function's name would be getNameValue, in your aspx page, you'd have a webmethod like this : (You'd basically transfer the code from Page_Load event to this)
[System.Web.Services.WebMethod]
public static Dictionary<string, string> getNameValue(string name, string keyN)
{
var schemaName = name;
var key = keyN;
Loader loader = ConnectionManager.getLoader();
Dictionary<string, string> name_value = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(schemaName))
{
var schema = loader.GetSchema(schemaName);
var qcontext = new SimpleLoader.BOService.QueryContext();
qcontext.InitQueryContext();
var element = loader.GetObjectByKey(schema, key);
var viselems = element._Schema.GetVisibleElems();
var cardElems = viselems.Where(x => !(x is SchemaElemDetail)).ToList();
foreach (var elem in cardElems)
{
var value = (element.GetValue(elem.Name) ?? "").ToString();
if (!string.IsNullOrEmpty(value))
{
name_value.Add(elem.Name, value);
}
}
}
return name_value; //will be automatically serialised to JSON because of the dataType specification in ajax call.
}
You'd invoke this function in jQuery in ready like this :
$(document).ready(function () {
var schemaName = GetURLParameters('schemaName');
var key = GetURLParameters('key');
//just in case
var data = JSON.stringify({
name: schemaName,
keyN: key
});
$.ajax({
type: "POST",
url: "dataloader.aspx/getNameValue",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message);
}
}).done(function (msg) {
//msg.d will contain your dictionary
});
});
The reason its better to use this method is that code becomes reusable. In your current set up, if you want to get the name_value dictionary you'd have to reload the aspx page. Now all you need to do is call this method.
Hope this helps!
It's best to convert to JSON from the DataLoader.aspx page. Then, add a callback in the code segment above:
$.post("dataloader.aspx", {
name: schemaName,
key: key,
success: function(d) { .. }
});
The variable "d" contains the response, which would probably be string. You can then use JQuery in the same way to send the data to the next page, either by using JSON.parse and parsing the content, or by passing JSON directly.
In order to create the JSON you want, you are going to need to serialize your dictionary. You can use System.Web.Script.Serialization.JavaScriptSerializer:
var JSSerializer = new JavaScriptSerializer();
Response.Write(JSSerializer.Serialize(name_value));
Then in your JS code:
$(document).ready(function () {
var schemaName = GetURLParameters('schemaName');
var key = GetURLParameters('key');
$.post("dataloader.aspx", {
name: schemaName,
key: key
}, function(data){
//Here is your success callback and data should be your JSON.
});
});
To make this cleaner you might want to consider using an HTTP handler template (.ashx) instead of an .aspx page so you won't have all the over head of an aspx page (i.e. code-behind and view).

Categories

Resources