calling function in the javascript written in webpage(.cs) - c#

I have function on .cs page
[System.Web.Services.WebMethod]
public static string getdata()
{
ProductBAL objbal = new ProductBAL(); // Calling class
int i = 0;
i = objbal.get_last_orderid(); //Select query
i = i + 1;
ProductDAL objdal = new ProductDAL(); // Calling class
objdal.insert_new_orderid(i); //Insert query
HttpCookie orderid = new HttpCookie("orderid");
orderid.Value = "MP_" + Convert.ToString(i);
Response.Cookies.Add(orderid);
Response.Cookies["orderid"].Expires = DateTime.Now.AddHours(5);
string abc=Convert.ToString(i);
return abc;
}
My Html page code is
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>calling function from .cs</title>
<script language="javascript" type="text/javascript">
function Submit1_onclick() {
$.ajax({ type: "GET", url: "default.aspx/getdata()", success: function (data) { });
alert("Done");
}
</script>
</head>
<body>
<form name="ecom" method="post" action="https://www.google.co.in/">
<input id="Submit1" type="submit" name="submit" runat="server" value="Submit" onclick="return Submit1_onclick()">
</form>
</body>
I am trying to call my web side function to client side on submit click.
Am I missing something? Please give a demo from my above code

function Submit1_onclick() {
// alert("Hello");
$.ajax({
type: "GET",
url: 'demo.aspx/getdata',
data: "{}",
//"{character:'M'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data.d);
//alert("success");
alert("This is ajax call:");
},
error: function() {
//alert(Error);
alert("something went wrong");
}
});
// alert("Done");
}
[WebMethod()] //U have to declare this method as a web method
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string getdata()
{

On your url try : "PageName.aspx/MethodName". Also check out this blog post by Dave Ward :
Using jQuery to directly call ASP.NET AJAX page methods

Below line is error prone. do not include "()" in url method name.
$.ajax({ type: "GET", url: "/getdata()", success: function (data) { });
Replace above line with
$.ajax({ type: "GET", url: "/getdata", success: function (data) { });

See the following working example
// Code behind method declared static
[WebMethod]
public static string GetSquare(String value)
{
return "hello" + value;
}
your button whose click this has to be done
<input type="button" id="button" value="Chnageurl" onclick="ajaxcall()" />
script for this
<script type="text/jscript">
function ajaxcall(e) {
$.ajax({
type: "POST",
url: "Default.aspx/GetSquare",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ value: "test" }),
dataType: "json",
success: function (value) {
alert(value.d);
},
error: function () { alert("Ajax Error"); }
});
};

From your comments I have gathered that you are verifying if this method is working by checking for new entries in a database table. The data in the database could be missing for other reasons rather than the query. To verify, try a more simple web method, and go from there.
eg,
Html :
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitClick();" />
Javascript :
function submitClick() {
$.ajax({
type: "POST",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "default.aspx/getdata",
success: function (data) {
console.log(data);
alert("success" + data);
},
error: function () {
alert("something went wrong");
}
});
return false; // Note: the return false will prevent postback
}
C#
[System.Web.Services.WebMethod]
public static string getdata()
{
return "Hello World!";
}
If you do not see a success response, then the problem is indeed with your javascript, or rather with the site setup which is somehow preventing callbacks from javascript.
If the method succeeds then it is likely that your database insertion script is raising an error and you should step through it to see that cause.

Related

MVC Ajax: How to send string from view to controller

I've found a small problem in sending just plain text(string) via ajax compared to sending an json object.
I have currently this setup working
(cs)html
<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />
Script
<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
and current controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);
}
I would like to just send a straight string to the controller and i tried this Script
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}
with this Controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);
}
however this didn't work, the input string was shown to get value of null and ajax gave error. I currently have no idea of how to fix this nor what gives the error. If someone could Point me in the right direction I would appreciate it
You can simply use the $.get function here and secondly you should use the Ùrl.Action helper for getting the url against the controller action method, as the magic strings would cause issues in deployments where the application might be deployed in sub-directories and in those case the url becomes wrong :
$.get('#Url.Action("SearchResults","Home")?input='+invalue , function (data) {
if (data.success) {
alert(data.message);
}
});
You can easily pass it as a request parameter, since you've also set the type to "GET".
url: "/Home/SearchResults?input="+invalue
You also have to remove the data attribute. Let me know if it helps.
UPDATED ANSWER
datatype is what you are expecting to return from the server. Content type is what you are sending. so to return a view change datatype to htmL.
dataType: 'html',
the problem is that when you call the function sendtoC you are not receiving any parameters in the function. Change the function to accept a parameter.
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC(invalue ) {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}

Uploading a file to an ASPX server-side page

I'm having trouble understanding how to send an uploaded file's content to my ASPX server-side. This is for an HTML-4 implementation where File API isn't available on the client-side, and using .NET v4.0.
Here's what I have so far:
HTML on FileReceiver.aspx:
<input type="button" id="uploadFile" value="Upload" />
<div class="hidden">
<form id="uploadFileForm">
<input type="file" id="browseForFiles" />
</form>
</div>
(client-side) JS:
$("#uploadFile").click(function () {
$("#browseForFiles").click();
});
$("#browseForFiles").change(function () {
$("#uploadFileForm").submit();
});
$("#uploadFileForm").submit(function (e) {
// prevent default action
e.preventDefault();
// send file to server
$.ajax({
url: "FileReceiver.aspx/ReceiveFile",
type: "post",
dataType: "multipart/form-data", // <---- is this right?
data: ???, // <-------------------------- what goes here?
success: function(data) {
// do something on success
}
});
});
(Server-side) FileReceiver.aspx.cs:
[WebMethod]
public static string ReceiveFile(??? receivedFile) // <-- what type goes here?
{
// do something and return status
}
Please help fill in the two "???" in the codes above. Thanks in advance!
This should work
$("#uploadFileForm").submit(function (e) {
// prevent default action
e.preventDefault();
var formData = new FormData($('#uploadFileForm')[0]);
$.ajax({
url: "FileReceiver.aspx/ReceiveFile",
type: "POST",
// Form data
data: formData, // <-- see above to see where this comes from
dataType: "json", // <-- the dataType you're RETURNING, not sending
cache: false,
//Options to tell jQuery not to process data or worry about content-type.
contentType: false,
processData: false,
success: function(data) {
// do something on success
}
});
});
Then your C# code should look like this
[WebMethod]
public static string ReceiveFile(HttpPostedFileBase receivedFile)
{
// do something and return status
}

Change page in browser after end of controller

How can i change page in browser, after end of controller?
I tryed this:
Html/JS code:
<form>
<button type="submit" onclick="abc()">123</button>
</form>
<script>
function abc()
{
$.post("/", "abc", function () {
});
}
</script>
ASP.NET MVC Code:
[HttpPost]
public ActionResult Index(dynamic response)
{
return Redirect(Request.UrlReferrer.ToString() + "/Home/OtherPage");
}
What am I doing wrong?
[HttpPost]
public ActionResult Index(dynamic response)
{
return RedirectToAction("OtherPage", "Home");
}
Check this solution -
Your Action should be like this -
public ActionResult RedirectMe()
{
return new JsonResult() { Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Then your JQuery POST should be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("RedirectMe")",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
window.location.href = data;
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
When you Click the button, you will be redirected to the Google. You have to make sure you construct a proper URL (instead of google) and send it back.
If you want to pass some parameters to Action, then follow this way -
public ActionResult RedirectMe(string id)
{
return new JsonResult(){ Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
Finally your JQuery POST should be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("RedirectMe")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: "This is my parameter"}),
success: function (data) {
window.location.href = data;
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
If you want to redirect to another page in your client code, You may send the new url in a JSON response and use window.location.href property to naviagate to that.
[HttpPost]
public ActionResult Index(dynamic response)
{
//Do your other work
string newUrl=Request.UrlReferrer.ToString() + "/Home/OtherPage";
//It may be better to use the Helper methods to get the url.
return Json(new { NewUrl=newUrl);
}
In your ajax call
$.post("YourURLHEre",{ response :YourDataHere},function(res){
window.location.href=res;
});

Redirect back to Default.aspx

I have a default.aspx (c#) page which has a simple Post AJAX call to a WebMethod that returns a JSON object, so that I can then populate a DataTable. All worked fine until I introduced a login page. Now, when a user is redirected to the Default page, after logging in, the Post never appears in FireBug.
This is my AJAX call:
$.ajax({
type: 'POST',
url: '/Default.aspx/GetValueDateSummary',
contentType: 'json',
data: {},
sucess: function (response) {
renderTable(response.d);
},
error: function (errMsg) {
$('#errorMessage').text(errMsg);
}
});
});
with the code behind being:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static List<ValueDateSummary> GetValueDateSummary()
{
some code in here.....
return drList;
}
sucess: function (response) {
should be
success: function (response) {
Are you using a ScriptManager object? If so, I believe that you need to enable page methods for it to work.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
Ok, i sorted it.
here is the complate Ajax call, seems i was missing the proper contentType and dataType
$.ajax({
type: 'POST',
url: 'Default.aspx/GetValueDateSummary',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
console.log(response);
alert(response.d);
renderTable(response.d);
},
error: function (errMsg) {
$('#errorMessage').text(errMsg);
}
});

Accessing page objects through static methods

I am using asp.net datepicker. Then executing a static event when a user clicks on a date through jquery like such:
<script>
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
$("#<%= lblDate.ClientID %>").text("Are available on " + $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val());
$.ajax({
type: "POST",
url: "Schedule.aspx/DisplayAvail",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Do something interesting here.
}
});
}
});
});
</script>
Code behind:
[WebMethod]
public static void DisplayAvail()
{
//Grab data from db to check avail from this date
}
Which works fine. But, from this static method there is no way to access page level objects. How can I send data from this method to the page?
Have a look here. You can get this via NuGet
http://james.newtonking.com/projects/json-net.aspx
Once you have the NewtonSoft Json dll added as a reference to your project which contains the webmethod, you can use JSONConvert to serialize your available dates and send it client side.
public IEnumerable<string> AvailableData {get; set;}
[WebMethod]
public static void DisplayAvail()
{
this.AvailableData = GetRequiredData();
this.AvailableData = JSONConvert.SerializeObject(this.AvailableData);
}
And on the client side, you can do:
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
$("#<%= lblDate.ClientID %>").text("Are available on " + $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val());
$.ajax({
type: "POST",
url: "Schedule.aspx/DisplayAvail",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var arr = <%= this.AvailableData %>;
$.each(arr, function(index, value) {
// Do something with the data
});
});
}
});
}
});
});
I decided the best rout to go is to use JQuery load() function to load an external page into the current page as such:
...Jquery
$("#GetData").load("getData.aspx?GetDate=012420012");
...html
<div id="GetData">
...
</div>
Thanks for all your feedback, but I think that this is the best way to go. Cheers! :)
You could try using PageMethods():
This is a simple tutorial Simple PageMethods example.
And also you need to do this:
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true" />
;)

Categories

Resources