I have been stuck on this for a few weeks, any help is very much appreciated!
I am building an MVC5 web application (This is my first C# & ASP.NET project). The model of this application is a web service. There is a page with a checkbox, and when clicked, this calls a bit of jQuery that uses AJAX to call a method in one of my controllers. This method calls a web service and updates a boolean value. This all seems to be working... my issue is that I need checkbox to be sent with the AJAX call, so that I can update a label on the page associated with the checkbox.
Is there a better way to accomplish this? (It seems rather hack-ish to me, using javascript to call my code). My question, though, is this: How can I pass the sender with an AJAX call?
CSHTML Page:
#Html.CheckBox("checkbox_subscribe", new{#id = "subscribeBox"})
#Html.Label("subscribebox", "Please notify me via email of any changes in lead times.")
<script>
$(document).ready(function () {
$("#subscribeBox").change(function (event) {
$.ajax({
type: "POST",
url: "#Url.Action("SubscribeClick", "Home")",
success: function (result) {
alert(result);
}
});
});
});
</script>
Controller Method:
public string SubscribeClick(object sender, EventArgs e)
{
String flag;
if (sender == checked)
{
flag = "Y";
}
else
{
flag = "N";
}
websecurity.n_securitySoapClient proxy = new websecurity.n_securitySoapClient();
String result = proxy.setsubscribeflag("11", flag, "leadtimes");
if (result.StartsWith("<success>"))
{
if (flag == "Y") result = "Successfully subscribed for email.";
else result = "Successfully unsubscribed from email.";
}
return result;
}
Just a side note: When I try casting the sender object to a CheckBox object type, I get the error: "InvalidCastException was unhandled by use code"
Ajax is client side code and has no concept of c# code such as object sender, EventArgs e. Change you method to accept a boolean
[HttpPost]
public ActionResult SubscribeClick(bool isChecked)
{
if(isChecked)
{
....
}
else
{
....
}
return Json(result,
}
and then in the script, pass true or false based on the state of the checkbox
$("#subscribeBox").change(function (event) {
var isChecked = $(this).is(':checked');
$.ajax({
type: "POST",
url: "#Url.Action("SubscribeClick", "Home")",
data: { isChecked: isChecked },
success: function (result) {
alert(result);
}
});
});
Related
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.
I am trying to pass a string value to a create item dialog, and am not sure on how to do it.
This is the code in my view:
JavaScript:
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}
View:
<td>#route</td>
<td>
Add
</td>
Controller:
public ActionResult Create(string routeName = "")
{
PopulateRouteInfoViewBag();
var newRoute = new RouteInformation();
newRoute.Name = routeName;
return View(newRoute);
}
I'm trying to take the value in #route and pass it over to the Create controller to have my dialog pop up with the passed in string value.
Use the ActionLink html helper method and pass the route variable like this.
#{
string route="somevaluehere";
}
#Html.ActionLink("Add","Create","YourControllerName",
new { routeName=route},new {#id="addLnk"})
Now handle the click event
$(function(){
$("#addLnk").click(function(e){
e.preventDefault(); //prevent normal link click behaviour
var _this=$(this);
//do your ajax call now
$.ajax({
url: _this.attr("href"),
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = 'someValidUrlHere'
else
$.facybox(data);
}
});
});
});
Also, You may consider building the path to the new page(action method) and return that as part of your JSON result and let the client read it from the JSON.
instead of appending the route variable value to the querystring, you may consider it as the part of message body.
There are two options. 1, use Url.Action("controllerName", "actionName", new {routeName = "your route name here"}) or 2, use the data property of the object passed into $.ajax.
For 2 your javascript would look something like
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
data: {
route: "your data here"
}
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}
I want to call a C# function in my aspx.cs file with jQuery. The function looks like:
protected void Fill(object sender, EventArgs e) { ...do s.th. with sender... }
in the function im getting my control I want to work with by doing a cast on the sender. How to pass the sender to server with jquery?
Check this : Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages
OR
Hi you can check this article : http://pranayamr.blogspot.com/2012/01/calling-server-side-function-from.html which dicuss about calling server method with the jQuery function.
cs file i.e serverside code
[WebMethod]
public static string IsExists(string value)
{ return "True"; }
Client script
function IsExists(pagePath, dataString, textboxid, errorlableid) {
//alert(pagePath);
$.ajax({
type: "POST",
url: pagePath,
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown) {
$(errorlableid).show();
$(errorlableid).html("Error");
},
success:
function(result) {
var flg = true;
if (result != null) {
debugger;
flg = result.d;
if (flg == "True") {
$(errorlableid).show();
}
else {
$(errorlableid).hide();
}
}
}
});
}
function focuslost() {
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'" + $("#<%= txtData.ClientID%>").val() + "' }";
var textboxid = "#<%= txtData.ClientID%>";
var errorlableid = "#<%= lblError.ClientID%>";
IsExists(pagePath, dataString, textboxid, errorlableid);
}
You can't call functions just like that with jQuery. jQuery is a client scripting technology based on javascript that runs on the client browser. It doesn't know what ASP.NET is. It even less knows what a server side, ASP.NET code behind method is.
This being said, you could send an AJAX request to a server side script which in your case could be either a generic handler (.ASHX) or an .ASPX page. In this second case you could use Page Methods.