I have created a javascript context menu using Jquery that works perfectly. But there are two options. The first one is to create this context menu in C# (If that's possible). The second way is to run a C# Function when a button in the menu is clicked. Which option is the best and how do i start? Kind regards
Javascript:
function Menu($div){
var that = this,
ts = null;
this.$div = $div;
this.items = [];
// create an item using a new closure
this.create = function(item){
var $item = $('<div class="item '+item.cl+'">'+item.label+'</div>');
$item
// bind click on item
.click(function(){
if (typeof(item.fnc) === 'function'){
item.fnc.apply($(this), []);
}
})
// manage mouse over coloration
.hover(
function(){$(this).addClass('hover');},
function(){$(this).removeClass('hover');}
);
return $item;
};
this.clearTs = function(){
if (ts){
clearTimeout(ts);
ts = null;
}
};
this.initTs = function(t){
ts = setTimeout(function(){that.close()}, t);
};
}
// add item
Menu.prototype.add = function(label, cl, fnc){
this.items.push({
label:label,
fnc:fnc,
cl:cl
});
}
// close previous and open a new menu
Menu.prototype.open = function(event){
this.close();
var k,
that = this,
offset = {
x:0,
y:0
},
$menu = $('<div id="menu"></div>');
// add items in menu
for(k in this.items){
$menu.append(this.create(this.items[k]));
}
// manage auto-close menu on mouse hover / out
$menu.hover(
function(){that.clearTs();},
function(){that.initTs(3000);}
);
// change the offset to get the menu visible (#menu width & height must be defined in CSS to use this simple code)
if ( event.pixel.y + $menu.height() > this.$div.height()){
offset.y = -$menu.height();
}
if ( event.pixel.x + $menu.width() > this.$div.width()){
offset.x = -$menu.width();
}
// use menu as overlay
this.$div.gmap3({
action:'addOverlay',
latLng: event.latLng,
content: $menu,
offset: offset
});
// start auto-close
this.initTs(5000);
}
// close the menu
Menu.prototype.close = function(){
this.clearTs();
this.$div.gmap3({action:'clear', name:'overlay'});
}
Well you could create a server control in C# and emit the menu from it, but since you already have a working menu it's just easier to call a server-side method in response to a click. If you're using jQuery it's as easy as:
$.ajax({
url: "/Path/To/MyMethod",
type: "POST",
dataType: "JSON",
data: <some POST data>,
contentType: "application/json; charset=utf-8",
success: function (result) {
// Do your stuff here
},
error: function (jqXHR, textStatus, errorThrown) {
// Report error
}
});
The implementation of the server-side part can be either a static [WebMethod] in an ASPX page, or if you're using MVC then it can be a direct call to a controller method.
I am assuming what you are trying to do is call a c# method when an Item on the context menu is selected. If you are using an MVC model this is pretty easy to do. Use a call as follows passing the parameters in JSON format. I am just using a skeleton method from my code as an example you would call LibraryRead method when you click on the Context Menu Link
Client Side
function LibraryRead() {
$.ajax({
url : 'Library/ReadLibrary',
type : "POST",
data : JSON.stringify(idLibrary),
dataType : "json",
contentType : "application/json; charset=utf-8",
success : function(result) {
$(result).each(function() {
....Process Results
});
},
error : function() {
.....If something goes wrong, if you use a try catch in your code
which does not handle the exception correctly and something goes wrong
this will not be triggered. Use propper exception handling.
}
});
}
Server Side
// Post: /Library/ReadLibrary
[HttpPost]
public JsonResult ReadLibrary(int idLibrary)
{
try
{
var library = READ your library here from your data source
return this.Json(library);
}
else
{
return null;
}
}
catch (Exception ex)
{
//Exception handling omitted for simplicity
}
}
Do a search on google for MVC3 and JQuery / Javascript calls with JSON, there are loads of resources available.
If you are not using MVC pattern you may be able to use a web service or method in the code behind. You need to add the appropriate attribute over the method though like [Ajax.AjaxMethod()] or [WebMethod]
Related
I'm working on an ASP.NET MVC C# app and need to recover an object (modelview) when a specific button is clicked in the view. I managed to send the value to the JsonResult controller but I don't get back anything from it.
This is the code from the button in my razor view:
$("#btn-buscar").click(function (e) {
$.ajax({
type: "POST",
url: '#Url.Action(actionName: "BISSS_Modificacion", controllerName: "Home")',
datatype: "Json",
//contentType: "application/json; charset=utf-8",
data: { ISSS: $("#idISSSBuscar").val()},
success: function (data) {
alert(data);
alert("todo bien " + data.Nombres);
}
});
});
and this is the JsonResult controller, it works since it retrieves the info
public JsonResult BISSS_Modificacion(string ISSS)
{
Entity BusquedaEmpleado = new Entity();
// here I retrieve the info from a Web API
if (respuestaBusqueda.respuesta)
{
BusquedaEmpleado.NombreM = respuestaBusqueda.nombres;
BusquedaEmpleado.ApellidoM = respuestaBusqueda.apellidos;
BusquedaEmpleado.DUIM = respuestaBusqueda.dui;
BusquedaEmpleado.ISSSM = respuestaBusqueda.numero_isss;
BusquedaEmpleado.CargoM = respuestaBusqueda.cargo_participante;
BusquedaEmpleado.SexoM = respuestaBusqueda.genero;
BusquedaEmpleado.NivelM = respuestaBusqueda.nivel_puesto;
BusquedaEmpleado.grupoM = Convert.ToInt32(respuestaBusqueda.grupo);
return Json(new { BusquedaEmpleado }, JsonRequestBehavior.AllowGet);
}
}
But when it comes to show the object in an alert window - the first alert in the click button code - this is what I get:
and if I what to show a specific value - the second alert in the click button code - this is what I get:
and if I use console.log to show the data, this is what I get:
Could you please tell me what am I doing wrong?
If I use alert(JSON.stringify(data)), I get this, which is the info I need so it looks like I getting the proper info (there are some null values but its ok):
and as you can see the prop for Apellido is ApellidoM but if I want to show that value in an alert window still got undefined -alert("todo bien " + JSON.stringify(data.ApellidoM));
Based on the result of the json stringify you posted, it looks like you just need to use the names of the properties that are actually on the JSON object.
alert("todo bien " + data.NombreM); // todo bien JOSE ANGER
I'm working with an asp.net MVC project. A coworker was new to MVC and handled all of the populating of data and click actions by using ajax calls. I know this isn't how MVC should be set up, but it's what I'm stuck with. I'm just trying to work around that the best I can. Anyway, within the method the ajax goes to, I need to redirect the user to a new page. How do I do that?
I tried Response.Redirect, but I got an error saying it didn't exist. I tried to add a using class, but couldn't it to work.
I found System.Diagnostics.Process.Start, but it opens in a new browser tab. Could there possibly be a way to open in the same tab?
So here's the ajax call. This is triggered in a javascript function when the user clicks a button:
$.ajax({
contentType: "application/json",
dataType: "json",
type: "post",
url: "/api/WoApi/PostWoApprGen/" + vUsr,
data: JSON.stringify(invObj),
success: function (res)
{
if (res)
{
var inv = $('#DivInv');
inv.html(res);
output = $('#TmpMsg');
output.html("");
opStatMsg("success", "rptGenWin");
}
else
{
opStatMsg("error", "rptGenWin");
}
}
});
That goes to a class in the controller directory, filename WoApiController.cs:
public string PostWoInv([FromBody] Koorsen.OpenAccess.WrkOrdTemp obj)
{
var currentUser = ClsUtility.GetCurrentUser();
if (currentUser == 0)
{
rep.UpdateWorkOrderStatusInvoiced(obj.WoTempId, currentUser, obj);
}
else
{
System.Diagnostics.Process.Start("~Admin/Login");
}
.............
.............
In your success callback, simply do
location.href = 'Home/Index';
or, preferably, using Razor and a method called Index in HomeController
location.href = '#Url.Action("Index", "Home")';
I am trying to edit a field after clicking an item from a table.
I added an on clcik event to every object in the table like this :
onclick="itemEdit(this)
And my javascript function looks something like :
function itemEdit(e) {
console.log($(e).attr("id"));
var itmId = $(e).attr("id");
$.ajax({
url: '#Url.Action("Index", "Scraping")',
data: {itemId: itmId},
type: 'POST',
success: function(data) {
alert(data);
}
});
}
And what I do in my Index method is to load the clicked item in a more detailed manner on the top of the page like this :
public ActionResult Index(string itemId)
{
if (itemId != null)
{
im.loadItem(itemId.ToString());
}
else
{
if (im.lstEditModel.Count == 0)
{
im.loadLists();
}
}
return RedirectToAction("Index");
}
The problem I am having is that whenever I click an item, the index method executes twice..and thus creating a mess. Any help?
I don't see an [HttpPost] mark on that method, but at the end of the method, you are redirecting to another Index action... you normally would return some sort of JSON data rather than return RedirectToAction("Index");... this statement would be doing what you are describing, calling your Get Action.
From MSDN:
Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action.
Try to stop event bubbling.
function itemEdit(e) {
e.stopPropagation();
console.log($(e).attr("id"));
var itmId = $(e).attr("id");
$.ajax({
url: '#Url.Action("Index", "Scraping")',
data: {itemId: itmId},
type: 'POST',
success: function(data) {
alert(data);
}
});
}
Please ignore this, by mistake I forgot to put href="#" when adding the onClick event causing the browser to reload my javascript code. I had typed href=""
So, I have done this before and made many many ajax calls
For some reason this one doesn't work =(
What do I need to change to get this one to work?
Previously I had an internal server error 500, but after pasting some working code and renaming methods to shorter names finally it changed over to this error of Unknown web method.
Setup
I am using jQuery to make Ajax calls to WebMethods in my Codebehind for my ASP.NET page.
Here is my C# WebMethod
[WebMethod(EnableSession = true)]
[ScriptMethod]
public string viewApps(string foo)
{
string x = "";
//130 lines of useful code.
x = "0";
return x;
}
Here is the Javascript/jQuery doing the ajax call. It is in side a with all my other ajax calls. The other ones work. This one does not. It triggered by an onclick event in the html.
function viewApps() {
var food = "hamburger";
$.ajax(
{
//send selected makes
type: "POST",
url: "MassUpdater.aspx/viewApps",
dataType: "json",
data: "{foo:" + food + "}",
contentType: "application/json; charset=utf-8",
//process the response
//and populate the list
success: function (msg) {
//just for show
},
error: function (e) {
alert(JSON.stringify(e));
$('#result').innerHTML = "unavailable";
}
});
//to be uncommented later when functionality works.
// populateBrakeConfigs();
// populateBedConfigs();
// populateBodyStyleConfigs();
// populateSpringConfigs();
// populateSteeringConfigs();
// populateWheeleBase();
// populateTransmission();
// populateDriveTypes();
function populateBrakeConfigs() { }
function populateBedConfigs() { }
function populateBodyStyleConfigs() { }
function populateSpringConfigs() { }
function populateSteeringConfigs() { }
function populateWheeleBase() { }
function populateTransmission() { }
function populateDriveTypes() { }
}
The ajax error looks like this:
I am also willing to provide any additional code or information about my project upon request.
The answer unfortunately is that somehow the static keyword got left out of the WebMethod, therefore the ajax call cannot find it.
This is with ASP.NET Web Forms .NET 2.0 -
I have a situation that I am not sure how to fulfill all the requirements. I need to update an img source on the page if selections are made from a drop down on the same page.
Basically, the drop downs are 'options' for the item. If a selection is made (i.e. color: red) then I would update the img for the product to something like (productID_red.jpeg) IF one exists.
The problem is I don't want to do post backs and refresh the page every time a selection is made - especially if I do a check to see if the image exists before I swap out the img src for that product and the file doesn't exist so I just refreshed the entire page for nothing.
QUESTION:
So I have easily thrown some javascript together that formulates a string of the image file name based on the options selected. My question is, what options do I have to do the following:
submit the constructed image name (i.e. productID_red_large.jpg) to some where that will verify the file exists either in C# or if it is even possible in the javascript. I also have to check for different possible file types (i.e. .png, .jpg...etc.).
not do a post back and refresh the entire page
Any suggestions?
submit the constructed image name
(i.e. productID_red_large.jpg) to some
where that will verify the file exists
either in C# or if it is even possible
in the javascript. I also have to
check for different possible file
types (i.e. .png, .jpg...etc.).
not do a post back and refresh the
entire page
If you wish to not post back to the page you will want to look at $.ajax() or $.post() (which is just short hand for $.ajax() with some default options)
To handle that request you could use a Generic Http Handler.
A simple outline could work like the following:
jQuery example for the post:
$("someButton").click(function () {
//Get the image name
var imageToCheck = $("#imgFileName").val();
//construct the data to send to the handler
var dataToSend = {
fileName: imageToCheck
};
$.post("/somePath/ValidateImage.ashx", dataToSend, function (data) {
if (data === "valid") {
//Do something
} else {
//Handle error
}
}, "html");
})
Then on your asp.net side you would create an http handler that will validate that request.
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var fileName = context.Request["fileName"];
var fullPath = Path.Combine("SomeLocalPath", fileName);
//Do something to validate the file
if (File.Exists(fullPath))
{
context.Response.Write("valid");
}
else
{
context.Response.Write("invalid");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Hope this helps, if I missed the mark at all on this let me know and I can revise.
We have an app of the same type, webforms .net 2, we do something similar with the following setup:
Using jQuery you can call a method in the page behind of the current page, for example, the following will trigger the AJAX call when the select box called selectBoxName changes, so your code work out the image name here and send it to the server.
$(document).ready(function () {
$('#selectBoxName').change(function (event) {
var image_name = 'calculated image name';
$.ajax({
type: "POST",
url: 'SomePage.aspx/CheckImageName',
data: "{'imageName': '" + image_name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function (a, b, c) {
alert("The image could not be loaded.");
}
});
});
});
Where SomePage.aspx is the current page name, and image_name is filled with the name you have already worked out. You could replace the img src in the success and error messages, again using jQuery.
The code behind for that page would then have a method like the following, were you could just reutrn true/fase or the correct image path as a string if needed. You can even return more complex types/objects and it will automatically send back the proper JSON resposne.
[System.Web.Services.WebMethod(true)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public static bool CheckImageName(string imageName)
{
/*
* Do some logic to check the file
if (file exists)
return true;
return false;
*/
}
As it is .net 2 app, you may need to install the AJAX Extensions:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en
Could you not use a normal ajax call to the physical path of the image and check if it returns a 404?
Like this:
http://stackoverflow.com/questions/333634/http-head-request-in-javascript-ajax
<script type="text/javascript">
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status != 404;
}
function ConstructImage() {
var e = document.getElementById("opt");
var url = '[yourpath]/' + e.value + '.jpg';
if (!UrlExists(url)) {
alert('doesnt exists');
//do stuff if doesnt exist
} else {
alert('exists');
//change img if it does
}
}
</script>
<select id="opt" onchange="ConstructImage()">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>